The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Replace inputAsk with pending tool calls on the conversation (#26988)
Félix Malfait98c3eb11fa18
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex 90e6866a9fa..912d30b79cf 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -4355,7 +4355,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")+ answerAgentChatQuestion(threadId: UUID!, messageId: UUID!, answers: [AgentChatQuestionAnswerInput!]!, modelId: String, fileAttachments: [FileAttachmentInput!]): SendChatMessageResult! @deprecated(reason: "Use answerToolCall with the questions tool call")createPublicDomain(domain: String!, applicationId: String!): PublicDomain!deletePublicDomain(domain: String!): Boolean!checkPublicDomainValidRecords(domain: String!): DomainValidRecordsdiff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex 19533e0962b..fcdaec05471 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -3748,7 +3748,7 @@ export interface Mutation {startChannelSync: ChannelSyncSuccesssaveImapSmtpCaldavAccount: ImapSmtpCaldavConnectionSuccessupdateLabPublicFeatureFlag: FeatureFlag- /** @deprecated Use answerAsk with the question's Ask */+ /** @deprecated Use answerToolCall with the questions tool call */answerAgentChatQuestion: SendChatMessageResultcreatePublicDomain: PublicDomaindeletePublicDomain: Scalars['Boolean']@@ -7723,7 +7723,7 @@ 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 */+ /** @deprecated Use answerToolCall with the questions tool call */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']} }diff --git a/packages/twenty-front/codegen-metadata.cjs b/packages/twenty-front/codegen-metadata.cjsindex 5ec1061b57e..acca989fedd 100644--- a/packages/twenty-front/codegen-metadata.cjs+++ b/packages/twenty-front/codegen-metadata.cjs@@ -9,6 +9,8 @@ module.exports = {'./src/modules/users/graphql/**/*.{ts,tsx}','./src/modules/views/graphql/**/*.{ts,tsx}','./src/modules/ai/graphql/**/*.{ts,tsx}',+ // answerToolCall is served by the core (/graphql) schema via @CoreResolver.+ '!./src/modules/ai/graphql/mutations/answerToolCall.ts','./src/modules/object-record/record-sharing/graphql/**/*.{ts,tsx}','./src/modules/applications/graphql/**/*.{ts,tsx}',diff --git a/packages/twenty-front/codegen.cjs b/packages/twenty-front/codegen.cjsindex 2f68ea8c357..342b4664fbc 100644--- a/packages/twenty-front/codegen.cjs+++ b/packages/twenty-front/codegen.cjs@@ -12,7 +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/modules/ai/graphql/mutations/answerToolCall.ts','!./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.tsindex b027ebd1c34..92fbceca559 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -3060,7 +3060,7 @@ export type Mutation = {activateSkill: Skill;activateWorkspace: Workspace;addQueryToEventStream: Scalars['Boolean']['output'];- /** @deprecated Use answerAsk with the question's Ask */+ /** @deprecated Use answerToolCall with the questions tool call */answerAgentChatQuestion: SendChatMessageResult;assignRoleToAgent: Scalars['Boolean']['output'];assignRoleToApiKey: Scalars['Boolean']['output'];diff --git a/packages/twenty-front/src/generated/graphql.ts b/packages/twenty-front/src/generated/graphql.tsindex 90070dca511..8804553e9b3 100644--- a/packages/twenty-front/src/generated/graphql.ts+++ b/packages/twenty-front/src/generated/graphql.ts@@ -18,15 +18,16 @@ export type Scalars = {UUID: { input: any; output: any; }};-export type AnswerAskInput = {- askId: Scalars['UUID']['input'];+export type AnswerToolCallInput = {modelId?: InputMaybe<Scalars['String']['input']>;- /** The answer, validated against what the Ask asked (its form kind) */+ /** The answer, validated against what the tool call asked */response: Scalars['JSON']['input'];+ threadId: Scalars['UUID']['input'];+ toolCallId: Scalars['String']['input'];};-export type AnswerAskResult = {- __typename?: 'AnswerAskResult';+export type AnswerToolCallResult = {+ __typename?: 'AnswerToolCallResult';streamId?: Maybe<Scalars['String']['output']>;};@@ -432,7 +433,7 @@ export type Mutation = {__typename?: 'Mutation';activateCoreWorkflowVersion: Scalars['Boolean']['output'];activateWorkflowVersion: Scalars['Boolean']['output'];- answerAsk: AnswerAskResult;+ answerToolCall: AnswerToolCallResult;computeStepOutputSchema: Scalars['JSON']['output'];createCoreWorkflow: CoreWorkflowDto;createCoreWorkflowVersionEdge: WorkflowVersionStepChanges;@@ -460,7 +461,7 @@ export type Mutation = {runCoreWorkflowVersion: RunWorkflowVersion;runWorkflowVersion: RunWorkflowVersion;stopWorkflowRun: WorkflowRun;- /** @deprecated Use answerAsk with the form step's Ask */+ /** @deprecated Use answerToolCall with the step's thread and the step id as toolCallId */submitFormStep: Scalars['Boolean']['output'];testHttpRequest: TestHttpRequest;updateCoreWorkflow?: Maybe<CoreWorkflowDto>;@@ -486,8 +487,8 @@ export type MutationActivateWorkflowVersionArgs = {};-export type MutationAnswerAskArgs = {- input: AnswerAskInput;+export type MutationAnswerToolCallArgs = {+ input: AnswerToolCallInput;};@@ -1217,6 +1218,13 @@ export type GetTimelineThreadsFromObjectRecordQueryVariables = Exact<{export type GetTimelineThreadsFromObjectRecordQuery = { __typename?: 'Query', getTimelineThreadsFromObjectRecord: { __typename?: 'TimelineThreadsWithTotal', totalNumberOfThreads: number, relatedPersonIds: Array<any>, timelineThreads: Array<{ __typename?: 'TimelineThread', id: any, read: boolean, visibility: MessageChannelVisibility, lastMessageReceivedAt: string, lastMessageBody: string, subject: string, numberOfMessagesInThread: number, participantCount: number, lastMessageIsDraft: boolean, firstParticipant: { __typename?: 'TimelineThreadParticipant', personId?: any | null, workspaceMemberId?: any | null, firstName: string, lastName: string, displayName: string, avatarUrl: string, handle: string }, lastTwoParticipants: Array<{ __typename?: 'TimelineThreadParticipant', personId?: any | null, workspaceMemberId?: any | null, firstName: string, lastName: string, displayName: string, avatarUrl: string, handle: string }> }> } };+export type AnswerToolCallMutationVariables = Exact<{+ input: AnswerToolCallInput;+}>;+++export type AnswerToolCallMutation = { __typename?: 'Mutation', answerToolCall: { __typename?: 'AnswerToolCallResult', streamId?: string | null } };+export type SearchQueryVariables = Exact<{searchInput: Scalars['String']['input'];limit: Scalars['Int']['input'];@@ -1229,13 +1237,6 @@ 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'];}>;@@ -1567,8 +1568,8 @@ export const TimelineThreadsWithTotalFragmentFragmentDoc = {"kind":"Document","dexport const WorkflowDiffFragmentFragmentDoc = {"kind":"Document","definitions":[{"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<WorkflowDiffFragmentFragment, unknown>;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 AnswerToolCallDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"AnswerToolCall"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"AnswerToolCallInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"answerToolCall"},"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<AnswerToolCallMutation, AnswerToolCallMutationVariables>;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>;diff --git a/packages/twenty-front/src/modules/ai/components/AiChatAskCard.tsx b/packages/twenty-front/src/modules/ai/components/AiChatAskCard.tsxindex 3a4da74f9ec..76d9f85dc5a 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatAskCard.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatAskCard.tsx@@ -1,36 +1,33 @@import { assertUnreachable } from 'twenty-shared/utils';import { AiChatEmailApprovalCard } from '@/ai/components/AiChatEmailApprovalCard';+import { AiChatFormCard } from '@/ai/components/AiChatFormCard';import { AiChatQuestionCard } from '@/ai/components/AiChatQuestionCard';-import { type AgentChatPendingAsk } from '@/ai/types/AgentChatPendingAsk';+import { type AgentChatPendingToolCall } from '@/ai/types/AgentChatPendingToolCall';type AiChatAskCardProps = {- pendingAsk: AgentChatPendingAsk;+ pendingToolCall: AgentChatPendingToolCall;};-export const AiChatAskCard = ({ pendingAsk }: AiChatAskCardProps) => {- const { id, toolCallId, form } = pendingAsk;-- switch (form.kind) {+export const AiChatAskCard = ({ pendingToolCall }: AiChatAskCardProps) => {+ switch (pendingToolCall.kind) {case 'questions':+ return <AiChatQuestionCard pendingQuestion={pendingToolCall} />;+ case 'emailApproval':return (- <AiChatQuestionCard- pendingQuestion={{- askId: id,- toolCallId,- questions: form.questions,- }}+ <AiChatEmailApprovalCard+ toolCallId={pendingToolCall.toolCallId}+ email={pendingToolCall.email}/>);- case 'emailApproval':+ case 'form':return (- <AiChatEmailApprovalCard- askId={id}- toolCallId={toolCallId}- email={form.email}+ <AiChatFormCard+ toolCallId={pendingToolCall.toolCallId}+ fields={pendingToolCall.fields}/>);default:- return assertUnreachable(form);+ return assertUnreachable(pendingToolCall);}};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsxindex cb6669ec904..1995449a064 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx@@ -5,6 +5,7 @@ import { RoutingStatusDisplay } from '@/ai/components/RoutingStatusDisplay';import { ThinkingStepsDisplay } from '@/ai/components/ThinkingStepsDisplay';import { AiChatEmailApprovalStatusRenderer } from '@/ai/components/AiChatEmailApprovalStatusRenderer';+import { AiChatFormStatusRenderer } from '@/ai/components/AiChatFormStatusRenderer';import { AiChatQuestionStatusRenderer } from '@/ai/components/AiChatQuestionStatusRenderer';import { AiChatToolPartRenderer } from '@/ai/components/AiChatToolPartRenderer';import { LazyMarkdownContent } from '@/ai/components/LazyMarkdownRenderer';@@ -23,6 +24,7 @@ import {type ExtendedUIMessagePart,isSucceededCompleteWorkspaceSetupToolPart,PROPOSE_EMAIL_TOOL_NAME,+ REQUEST_FORM_TOOL_NAME,} from 'twenty-shared/ai';import { themeCssVariables } from 'twenty-ui/theme';@@ -81,6 +83,15 @@ const MessagePartRenderer = ({);}+ if (getToolName(part) === REQUEST_FORM_TOOL_NAME) {+ return (+ <AiChatFormStatusRenderer+ 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.tsxindex c64b0ab8eb4..65c516d58ef 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx@@ -7,9 +7,6 @@ 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';@@ -31,14 +28,10 @@ import { useInsertDictatedText } from '@/ai/dictation/hooks/useInsertDictatedTeximport { useIsAiChatComposerCentered } from '@/ai/hooks/useIsAiChatComposerCentered';import { useHasReachedAiChatCreditsCap } from '@/ai/hooks/useHasReachedAiChatCreditsCap';import { useHasReachedAiChatUsageLimit } from '@/ai/hooks/useHasReachedAiChatUsageLimit';-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';-import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';import { agentChatHasMessageComponentSelector } from '@/ai/states/selectors/agentChatHasMessageComponentSelector';-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)<{@@ -177,20 +170,6 @@ const EditableAiChatEditorSection = () => {const insertDictatedText = useInsertDictatedText(editor);const [dictationInterimText, setDictationInterimText] = useState('');- 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(agentChatDisplayedThread) &&- agentChatDisplayedThread !== AGENT_CHAT_NEW_THREAD_DRAFT_KEY- ? agentChatDisplayedThread- : null;-const composer = (<StyledInputBox isMobile={isMobile}><StyledEditorWrapper isMobile={isMobile}>@@ -247,13 +226,7 @@ const EditableAiChatEditorSection = () => {)}{hasReachedAiChatCreditsCap && <AIChatNoMoreBillingCreditsBanner />}{shouldShowUsageLimitBanner && <AiChatUsageLimitReachedBanner />}- {isDefined(inputAskObjectMetadataItem) ? (- <AiChatPendingAskGate threadId={pendingAskThreadId}>- {composer}- </AiChatPendingAskGate>- ) : (- composer- )}+ <AiChatPendingAskGate>{composer}</AiChatPendingAskGate></StyledInputArea><StyledComposerBottomSpacerclassName={isComposerCentered ? 'is-centered' : undefined}diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEmailApprovalCard.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEmailApprovalCard.tsxindex 16c864de249..773441f0bc5 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatEmailApprovalCard.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatEmailApprovalCard.tsx@@ -4,7 +4,7 @@ import { type FocusEvent, useId, useState } from 'react';import TextareaAutosize from 'react-textarea-autosize';import {type EmailApprovalDecision,- type InputAskEmailApprovalResponse,+ type EmailApprovalResponse,type ProposeEmailToolResult,type ProposedEmail,} from 'twenty-shared/ai';@@ -17,7 +17,7 @@ import { parseEmailRecipients } from '@/activities/emails/recipients/utils/parseimport { 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 { useAnswerAgentChatToolCall } from '@/ai/hooks/useAnswerAgentChatToolCall';import { usePushFocusItemToFocusStack } from '@/ui/utilities/focus/hooks/usePushFocusItemToFocusStack';import { useRemoveFocusItemFromFocusStackById } from '@/ui/utilities/focus/hooks/useRemoveFocusItemFromFocusStackById';import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';@@ -79,19 +79,17 @@ const StyledActions = styled.div``;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 { answerAgentChatToolCall } = useAnswerAgentChatToolCall();const { pushFocusItemToFocusStack } = usePushFocusItemToFocusStack();const { removeFocusItemFromFocusStackById } =useRemoveFocusItemFromFocusStackById();@@ -149,11 +147,10 @@ export const AiChatEmailApprovalCard = ({subject,body,};- const response: InputAskEmailApprovalResponse =+ const response: EmailApprovalResponse =decision === 'discard' ? { decision } : { decision, email: editedEmail };- const isAnswered = await answerAgentChatAsk({- askId,+ const isAnswered = await answerAgentChatToolCall({toolCallId,response,// Only a discard is known before the server answers: sending or saving@@ -170,7 +167,7 @@ export const AiChatEmailApprovalCard = ({: undefined,});- // The card goes once its Ask does, so it stays disabled until then.+ // The card goes once its call is closed, so it stays disabled until then.if (!isAnswered) {setPendingDecision(null);}diff --git a/packages/twenty-front/src/modules/ai/components/AiChatFormCard.tsx b/packages/twenty-front/src/modules/ai/components/AiChatFormCard.tsxnew file mode 100644index 00000000000..2ab2e7dced7--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatFormCard.tsx@@ -0,0 +1,89 @@+import { styled } from '@linaria/react';+import { useLingui } from '@lingui/react/macro';+import { useState } from 'react';+import {+ type RequestFormField,+ type RequestFormToolResult,+} from 'twenty-shared/ai';+import { isDefined } from 'twenty-shared/utils';+import { Button } from 'twenty-ui/primitives/input';+import { themeCssVariables } from 'twenty-ui/theme';++import { StyledAiChatAskCard } from '@/ai/components/AiChatAskStyledComponents';+import { useAnswerAgentChatToolCall } from '@/ai/hooks/useAnswerAgentChatToolCall';+import { WorkflowFormFields } from '@/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFields';++const StyledFields = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[3]};+ padding: ${themeCssVariables.spacing[3]};+`;++const StyledActions = styled.div`+ border-top: 1px solid ${themeCssVariables.border.color.light};+ display: flex;+ justify-content: flex-end;+ padding: ${themeCssVariables.spacing[2]};+`;++type AiChatFormCardProps = {+ toolCallId: string;+ fields: RequestFormField[];+};++export const AiChatFormCard = ({ toolCallId, fields }: AiChatFormCardProps) => {+ const { t } = useLingui();+ const { answerAgentChatToolCall } = useAnswerAgentChatToolCall();+ const [values, setValues] = useState<Record<string, unknown>>({});+ const [error, setError] = useState<string | undefined>(undefined);+ const [isSubmitting, setIsSubmitting] = useState(false);++ const submit = async () => {+ setIsSubmitting(true);++ const isAnswered = await answerAgentChatToolCall({+ toolCallId,+ response: values,+ optimisticToolOutput: {+ success: true,+ result: { status: 'answered', values } satisfies RequestFormToolResult,+ },+ });++ // The card goes once its call is closed, so it stays disabled until then.+ if (!isAnswered) {+ setIsSubmitting(false);+ }+ };++ return (+ <StyledAiChatAskCard>+ <StyledFields>+ <WorkflowFormFields+ fields={fields}+ readonly={isSubmitting}+ onChange={(fieldName, value) =>+ setValues((previousValues) => ({+ ...previousValues,+ [fieldName]: value,+ }))+ }+ onError={setError}+ />+ </StyledFields>+ <StyledActions>+ <Button+ size="sm"+ variant="solid"+ color="accent"+ disabled={isSubmitting || isDefined(error)}+ loading={isSubmitting}+ onClick={() => void submit()}+ >+ {t`Submit`}+ </Button>+ </StyledActions>+ </StyledAiChatAskCard>+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatFormStatusRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatFormStatusRenderer.tsxnew file mode 100644index 00000000000..e284d98df45--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatFormStatusRenderer.tsx@@ -0,0 +1,85 @@+import { styled } from '@linaria/react';+import { useLingui } from '@lingui/react/macro';+import { isString } from '@sniptt/guards';+import { type DynamicToolUIPart, type ToolUIPart } from 'ai';+import {+ type RequestFormToolInput,+ type RequestFormToolResult,+} from 'twenty-shared/ai';+import { isDefined } from 'twenty-shared/utils';+import { IconListDetails } 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 AiChatFormStatusRenderer = ({+ toolPart,+ isStreaming,+}: {+ toolPart: ToolUIPart | DynamicToolUIPart;+ isStreaming: boolean;+}) => {+ const { t } = useLingui();+ const theme = useTheme();++ const fields =+ (toolPart.input as Partial<RequestFormToolInput> | undefined)?.fields ?? [];+ const result = (+ toolPart.output as { result?: RequestFormToolResult } | null | undefined+ )?.result;+ const status = result?.status ?? 'pending';+ const values = result?.values ?? {};++ const messageByStatus = {+ pending: t`Waiting for a form to be filled in`,+ answered: t`Form submitted`,+ skipped: t`Form skipped`,+ };++ return (+ <StyledAiChatAskStatusContainer>+ <IconListDetails size={theme.icon.size.sm} />+ <StyledContent>+ {isStreaming && status === 'pending' ? (+ <ShimmeringText>+ <StyledAiChatAskStatusMessage>+ {messageByStatus[status]}+ </StyledAiChatAskStatusMessage>+ </ShimmeringText>+ ) : (+ <StyledAiChatAskStatusMessage>+ {messageByStatus[status]}+ </StyledAiChatAskStatusMessage>+ )}+ {fields+ .filter((field) => isDefined(values[field.name]))+ .map((field) => {+ const value = values[field.name];++ return (+ <StyledDetail key={field.name}>+ {`${field.label}: ${isString(value) ? value : JSON.stringify(value)}`}+ </StyledDetail>+ );+ })}+ </StyledContent>+ </StyledAiChatAskStatusContainer>+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsxindex 9f5582e16cf..6f7af1881e2 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx@@ -5,7 +5,7 @@ import { isDefined } from 'twenty-shared/utils';import { themeCssVariables } from 'twenty-ui/theme';import { AiChatAskCard } from '@/ai/components/AiChatAskCard';-import { useAgentChatPendingAsks } from '@/ai/hooks/useAgentChatPendingAsks';+import { useAgentChatPendingToolCalls } from '@/ai/hooks/useAgentChatPendingToolCalls';const StyledGate = styled.div`display: flex;@@ -21,25 +21,23 @@ const StyledWaitingCount = styled.span``;type AiChatPendingAskGateProps = {- threadId: string | null;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;+ const pendingToolCalls = useAgentChatPendingToolCalls();+ const [currentToolCall] = pendingToolCalls;- if (!isDefined(currentAsk)) {+ if (!isDefined(currentToolCall)) {return children;}- const waitingCount = pendingAsks.length;+ const waitingCount = pendingToolCalls.length;return (<StyledGate>@@ -48,7 +46,10 @@ export const AiChatPendingAskGate = ({{t`${waitingCount} requests are waiting on you`}</StyledWaitingCount>)}- <AiChatAskCard key={currentAsk.id} pendingAsk={currentAsk} />+ <AiChatAskCard+ key={currentToolCall.toolCallId}+ pendingToolCall={currentToolCall}+ /></StyledGate>);};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsx b/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsxindex 33a206b8e65..a891db6c8fc 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsx@@ -32,7 +32,7 @@ import { AiModelTierDropdown } from '@/ai/components/AiModelTierDropdown';import { TextWithChatReferences } from '@/ai/components/TextWithChatReferences';import { AiChatContextUsageButton } from '@/ai/components/internal/AiChatContextUsageButton';import { AiChatQuestionOtherOption } from '@/ai/components/internal/AiChatQuestionOtherOption';-import { useAnswerAgentChatAsk } from '@/ai/hooks/useAnswerAgentChatAsk';+import { useAnswerAgentChatToolCall } from '@/ai/hooks/useAnswerAgentChatToolCall';import { type AgentChatPendingQuestion } from '@/ai/types/AgentChatPendingQuestion';import { aiModelsState } from '@/client-config/states/aiModelsState';import { TooltipDelay } from '@/ui/layout/tooltip/constants/TooltipDelay';@@ -197,7 +197,7 @@ export const AiChatQuestionCard = ({}: AiChatQuestionCardProps) => {const { t } = useLingui();const theme = useTheme();- const { askId, toolCallId, questions } = pendingQuestion;+ const { toolCallId, questions } = pendingQuestion;const [currentIndex, setCurrentIndex] = useState(0);const [selectedByQuestion, setSelectedByQuestion] = useState<@@ -211,7 +211,7 @@ export const AiChatQuestionCard = ({>({});const [isSubmitting, setIsSubmitting] = useState(false);- const { answerAgentChatAsk } = useAnswerAgentChatAsk();+ const { answerAgentChatToolCall } = useAnswerAgentChatToolCall();const aiModels = useAtomStateValue(aiModelsState);const hasNoEnabledModels = aiModels.length === 0;@@ -243,8 +243,7 @@ export const AiChatQuestionCard = ({setIsSubmitting(true);- const isAnswered = await answerAgentChatAsk({- askId,+ const isAnswered = await answerAgentChatToolCall({toolCallId,response: { answers },optimisticToolOutput: {@@ -257,7 +256,7 @@ export const AiChatQuestionCard = ({},});- // The card goes once its Ask does, so it stays disabled until then.+ // The card goes once its call is closed, so it stays disabled until then.if (!isAnswered) {setIsSubmitting(false);}diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatFormCard.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatFormCard.stories.tsxnew file mode 100644index 00000000000..fbd1c52d272--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatFormCard.stories.tsx@@ -0,0 +1,82 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { useStore } from 'jotai';+import { type ReactNode, useEffect } from 'react';+import { FieldMetadataType } from 'twenty-shared/types';+import { ComponentDecorator } from 'twenty-ui/testing';++import { AiChatFormCard } from '@/ai/components/AiChatFormCard';+import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';+import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';++import { styled } from '@linaria/react';+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';+import { RootDecorator } from '~/testing/decorators/RootDecorator';+import { ToastDecorator } from '~/testing/decorators/ToastDecorator';++const StyledContainer = styled.div`+ max-width: 400px;+ padding: 24px;+`;++const StoreSeeder = ({ children }: { children: ReactNode }) => {+ const store = useStore();++ useEffect(() => {+ store.set(currentAiChatThreadState.atom, 'thread-1');+ store.set(agentChatDisplayedThreadState.atom, 'thread-1');+ }, [store]);++ return <>{children}</>;+};++const meta: Meta<typeof AiChatFormCard> = {+ title: 'Modules/AiChat/AiChatFormCard',+ component: AiChatFormCard,+ decorators: [+ (Story) => (+ <AgentChatComponentInstanceContext.Provider+ value={{ instanceId: 'agentChatFormCardStory' }}+ >+ <StoreSeeder>+ <StyledContainer>+ <Story />+ </StyledContainer>+ </StoreSeeder>+ </AgentChatComponentInstanceContext.Provider>+ ),+ ToastDecorator,+ ComponentDecorator,+ MemoryRouterDecorator,+ RootDecorator,+ ],+};++export default meta;++type Story = StoryObj<typeof AiChatFormCard>;++export const Default: Story = {+ args: {+ toolCallId: 'call-1',+ fields: [+ {+ name: 'amount',+ label: 'Amount (USD)',+ type: FieldMetadataType.NUMBER,+ placeholder: '50000',+ },+ {+ name: 'closeDate',+ label: 'Expected close',+ type: FieldMetadataType.DATE,+ },+ {+ name: 'nextStep',+ label: 'Next step',+ type: FieldMetadataType.TEXT,+ placeholder: 'Security review with their IT team',+ },+ ],+ },+};diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatMessage.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatMessage.stories.tsxindex ff6370aeb55..448c2f475e9 100644--- a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatMessage.stories.tsx+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatMessage.stories.tsx@@ -239,6 +239,37 @@ const mockThinkingStepsDone: ExtendedUIMessage = {},};+const mockAnsweredForm: ExtendedUIMessage = {+ id: 'msg-answered-form',+ role: 'assistant',+ parts: [+ {+ type: 'tool-request_form',+ toolCallId: 'tool-request-form',+ input: {+ fields: [+ { name: 'callDate', label: 'Call date', type: 'DATE' },+ { name: 'summary', label: 'Summary', type: 'TEXT' },+ ],+ },+ output: {+ success: true,+ result: {+ status: 'answered',+ values: {+ callDate: '2026-09-29',+ summary: 'Pipeline import first, SSO the week after.',+ },+ },+ },+ state: 'output-available',+ },+ ],+ metadata: {+ createdAt: new Date().toISOString(),+ },+};+const allMockMessages = [mockUserMessage,mockAssistantWithCodeExecution,@@ -248,6 +279,7 @@ const allMockMessages = [mockCodeExecutionError,mockThinkingStepsStreaming,mockThinkingStepsDone,+ mockAnsweredForm,];const AgentChatMessagesSetterEffect = ({@@ -360,3 +392,7 @@ export const ThinkingStepsDoneExpanded: Story = {await userEvent.click(summaryButton);},};++export const AnsweredForm: Story = {+ render: () => <AiChatMessage messageId={mockAnsweredForm.id} />,+};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.tsxindex 95a2631df08..3116309ab73 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,6 @@ const StyledContainer = styled.div`const INSTANCE_ID = 'agentChatQuestionCardStory';const singleQuestion: AgentChatPendingQuestion = {- askId: 'ask-1',toolCallId: 'call-1',questions: [{@@ -43,7 +42,6 @@ const singleQuestion: AgentChatPendingQuestion = {};const multipleQuestions: AgentChatPendingQuestion = {- askId: 'ask-2',toolCallId: 'call-2',questions: [singleQuestion.questions[0],@@ -59,7 +57,6 @@ const multipleQuestions: AgentChatPendingQuestion = {};const longQuestion: AgentChatPendingQuestion = {- askId: 'ask-3',toolCallId: 'call-3',questions: [{@@ -78,7 +75,6 @@ const longQuestion: AgentChatPendingQuestion = {};const multiSelectQuestion: AgentChatPendingQuestion = {- 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.tsxindex 26066315e99..86b9e061958 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,7 +19,7 @@ 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+// The gate's cards pull in the form fields' 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,diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.test.tsxindex 03aff21a5c1..7f041c80156 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.test.tsx@@ -37,15 +37,7 @@ const objectMetadataItems = getTestEnrichedObjectMetadataItemsMock();const renderEditorSectionOnNewChat = () => {const MetadataAndApolloWrapper = getJestMetadataAndApolloMocksWrapper({- objectMetadataItems: [- ...objectMetadataItems,- {- ...objectMetadataItems[0],- id: '20202020-1b2c-4d3e-8f4a-5b6c7d8e9f0a',- nameSingular: 'inputAsk',- namePlural: 'inputAsks',- },- ],+ objectMetadataItems,onInitializeJotaiStore: (store) => {store.set(currentAiChatThreadState.atom, AGENT_CHAT_NEW_THREAD_DRAFT_KEY);store.set(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.tsxindex 39a4e1187db..42043ca469c 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEmailApprovalCard.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEmailApprovalCard.test.tsx@@ -6,9 +6,9 @@ import { createStore, Provider } from 'jotai';import { AiChatEmailApprovalCard } from '@/ai/components/AiChatEmailApprovalCard';-const answerAgentChatAsk = jest.fn();-jest.mock('@/ai/hooks/useAnswerAgentChatAsk', () => ({- useAnswerAgentChatAsk: () => ({ answerAgentChatAsk }),+const answerAgentChatToolCall = jest.fn();+jest.mock('@/ai/hooks/useAnswerAgentChatToolCall', () => ({+ useAnswerAgentChatToolCall: () => ({ answerAgentChatToolCall }),}));const EMAIL = {@@ -22,23 +22,19 @@ const renderCard = () =>render(<I18nProvider i18n={i18n}><Provider store={createStore()}>- <AiChatEmailApprovalCard- askId="ask-1"- toolCallId="call-1"- email={EMAIL}- />+ <AiChatEmailApprovalCard toolCallId="call-1" email={EMAIL} /></Provider></I18nProvider>,);describe('AiChatEmailApprovalCard', () => {beforeEach(() => {- answerAgentChatAsk.mockReset();+ answerAgentChatToolCall.mockReset();});it('sends the email as the person edited it', async () => {const user = userEvent.setup();- answerAgentChatAsk.mockReturnValue(new Promise(() => {}));+ answerAgentChatToolCall.mockReturnValue(new Promise(() => {}));renderCard();@@ -47,8 +43,7 @@ describe('AiChatEmailApprovalCard', () => {await user.type(subject, 'Renewal confirmed');await user.click(screen.getByRole('button', { name: 'Send' }));- expect(answerAgentChatAsk).toHaveBeenCalledWith({- askId: 'ask-1',+ expect(answerAgentChatToolCall).toHaveBeenCalledWith({toolCallId: 'call-1',response: {decision: 'send',@@ -65,7 +60,7 @@ describe('AiChatEmailApprovalCard', () => {it('saves a draft to the recipients the person chose', async () => {const user = userEvent.setup();- answerAgentChatAsk.mockResolvedValue(true);+ answerAgentChatToolCall.mockResolvedValue(true);renderCard();@@ -78,7 +73,7 @@ describe('AiChatEmailApprovalCard', () => {);await user.click(screen.getByRole('button', { name: 'Save as draft' }));- expect(answerAgentChatAsk).toHaveBeenCalledWith(+ expect(answerAgentChatToolCall).toHaveBeenCalledWith(expect.objectContaining({response: {decision: 'saveDraft',@@ -130,14 +125,13 @@ describe('AiChatEmailApprovalCard', () => {it('discards the email without sending it, and shows it discarded right away', async () => {const user = userEvent.setup();- answerAgentChatAsk.mockResolvedValue(true);+ answerAgentChatToolCall.mockResolvedValue(true);renderCard();await user.click(screen.getByRole('button', { name: 'Discard' }));- expect(answerAgentChatAsk).toHaveBeenCalledWith({- askId: 'ask-1',+ expect(answerAgentChatToolCall).toHaveBeenCalledWith({toolCallId: 'call-1',response: { decision: 'discard' },optimisticToolOutput: {@@ -149,7 +143,7 @@ describe('AiChatEmailApprovalCard', () => {it('lets the person decide again when the answer is refused', async () => {const user = userEvent.setup();- answerAgentChatAsk.mockResolvedValue(false);+ answerAgentChatToolCall.mockResolvedValue(false);renderCard();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.tsxindex 25b9af73ea2..b9883a52dba 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPendingAskGate.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPendingAskGate.test.tsx@@ -1,15 +1,18 @@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 {+ type AskQuestionItem,+ type ProposedEmail,+ type RequestFormField,+} 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),+const useAgentChatPendingToolCalls = jest.fn();+jest.mock('@/ai/hooks/useAgentChatPendingToolCalls', () => ({+ useAgentChatPendingToolCalls: () => useAgentChatPendingToolCalls(),}));jest.mock('@/ai/components/AiChatQuestionCard', () => ({AiChatQuestionCard: ({@@ -22,6 +25,13 @@ jest.mock('@/ai/components/AiChatQuestionCard', () => ({</div>),}));+jest.mock('@/ai/components/AiChatFormCard', () => ({+ AiChatFormCard: ({ fields }: { fields: RequestFormField[] }) => (+ <div role="group" aria-label="Form">+ {fields[0].label}+ </div>+ ),+}));jest.mock('@/ai/components/AiChatEmailApprovalCard', () => ({AiChatEmailApprovalCard: ({ email }: { email: ProposedEmail }) => (<div role="group" aria-label="Email approval">@@ -38,23 +48,20 @@ const QUESTIONS: AskQuestionItem[] = [},];-const EMAIL_ASK = {- id: 'ask-2',+const EMAIL_APPROVAL = {toolCallId: 'call-2',- form: {- kind: 'emailApproval',- email: {- recipients: { to: '[email protected]', cc: '', bcc: '' },- subject: 'Your renewal',- body: 'Hi Tim',- },+ 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">+ <AiChatPendingAskGate><textarea aria-label="Message" /></AiChatPendingAskGate></I18nProvider>,@@ -62,19 +69,12 @@ const renderGate = () =>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 },- },+ useAgentChatPendingToolCalls.mockReturnValue([+ { toolCallId: 'call-1', kind: 'questions', questions: QUESTIONS },]);renderGate();- expect(useAgentChatPendingAsks).toHaveBeenCalledWith({- threadId: 'thread-id',- });expect(screen.getByRole('group', { name: 'Questions' })).toHaveTextContent('Which plan?',);@@ -82,7 +82,7 @@ describe('AiChatPendingAskGate', () => {});it('shows an email waiting for approval in place of the composer', () => {- useAgentChatPendingAsks.mockReturnValue([EMAIL_ASK]);+ useAgentChatPendingToolCalls.mockReturnValue([EMAIL_APPROVAL]);renderGate();@@ -92,18 +92,31 @@ describe('AiChatPendingAskGate', () => {expect(screen.queryByRole('textbox', { name: 'Message' })).toBeNull();});- it('shows the oldest of several requests first and says how many wait', () => {- useAgentChatPendingAsks.mockReturnValue([- EMAIL_ASK,+ it('shows a form to fill in place of the composer', () => {+ useAgentChatPendingToolCalls.mockReturnValue([{- id: 'ask-3',- toolCallId: 'call-3',- form: { kind: 'questions', questions: QUESTIONS },+ toolCallId: 'call-4',+ kind: 'form',+ fields: [{ name: 'closeDate', label: 'Close date', type: 'DATE' }],},]);renderGate();+ expect(screen.getByRole('group', { name: 'Form' })).toHaveTextContent(+ 'Close date',+ );+ expect(screen.queryByRole('textbox', { name: 'Message' })).toBeNull();+ });++ it('shows the oldest of several requests first and says how many wait', () => {+ useAgentChatPendingToolCalls.mockReturnValue([+ EMAIL_APPROVAL,+ { toolCallId: 'call-3', kind: 'questions', questions: QUESTIONS },+ ]);++ renderGate();+expect(screen.getByRole('group', { name: 'Email approval' }),).toHaveTextContent('Your renewal');@@ -115,7 +128,7 @@ describe('AiChatPendingAskGate', () => {});it('shows the composer once nothing is pending', () => {- useAgentChatPendingAsks.mockReturnValue([]);+ useAgentChatPendingToolCalls.mockReturnValue([]);renderGate();diff --git a/packages/twenty-front/src/modules/ai/constants/PausingToolNames.ts b/packages/twenty-front/src/modules/ai/constants/PausingToolNames.tsindex f004051cd9c..45c639bc369 100644--- a/packages/twenty-front/src/modules/ai/constants/PausingToolNames.ts+++ b/packages/twenty-front/src/modules/ai/constants/PausingToolNames.ts@@ -1,10 +1,12 @@import {ASK_QUESTIONS_TOOL_NAME,PROPOSE_EMAIL_TOOL_NAME,+ REQUEST_FORM_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,+ REQUEST_FORM_TOOL_NAME,]);diff --git a/packages/twenty-front/src/modules/ai/graphql/mutations/answerToolCall.ts b/packages/twenty-front/src/modules/ai/graphql/mutations/answerToolCall.tsnew file mode 100644index 00000000000..52bcc933458--- /dev/null+++ b/packages/twenty-front/src/modules/ai/graphql/mutations/answerToolCall.ts@@ -0,0 +1,9 @@+import { gql } from '@apollo/client';++export const ANSWER_TOOL_CALL = gql`+ mutation AnswerToolCall($input: AnswerToolCallInput!) {+ answerToolCall(input: $input) {+ streamId+ }+ }+`;diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatPendingToolCalls.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatPendingToolCalls.test.tsxnew file mode 100644index 00000000000..ff3b0756a0b--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatPendingToolCalls.test.tsx@@ -0,0 +1,81 @@+import { renderHook } from '@testing-library/react';+import { Provider } from 'jotai';+import { type ReactNode } from 'react';+import { type ExtendedUIMessage } from 'twenty-shared/ai';++import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';+import { useAgentChatPendingToolCalls } from '@/ai/hooks/useAgentChatPendingToolCalls';+import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';+import { agentChatIsStreamingComponentFamilyState } from '@/ai/states/agentChatIsStreamingComponentFamilyState';+import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';+import {+ jotaiStore,+ resetJotaiStore,+} from '@/ui/utilities/state/jotai/jotaiStore';++const key = {+ instanceId: 'pending-test',+ familyKey: { threadId: 'thread-id' },+};++const QUESTIONS = [{ header: 'Plan', question: 'Which plan?', options: [] }];++const questionsCall = (toolCallId: string, status: string) => ({+ type: 'tool-ask_questions',+ toolCallId,+ state: 'output-available',+ input: { questions: QUESTIONS },+ output: { success: true, result: { questions: QUESTIONS, status } },+});++const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider store={jotaiStore}>+ <AgentChatComponentInstanceContext.Provider+ value={{ instanceId: 'pending-test' }}+ >+ {children}+ </AgentChatComponentInstanceContext.Provider>+ </Provider>+);++describe('useAgentChatPendingToolCalls', () => {+ beforeEach(() => {+ resetJotaiStore();+ jotaiStore.set(agentChatDisplayedThreadState.atom, 'thread-id');+ jotaiStore.set(agentChatMessagesComponentFamilyState.atomFamily(key), [+ {+ id: 'assistant-1',+ role: 'assistant',+ parts: [+ { type: 'text', text: 'Two things first:' },+ questionsCall('call-answered', 'answered'),+ questionsCall('call-1', 'pending'),+ questionsCall('call-2', 'pending'),+ ],+ },+ ] as unknown as ExtendedUIMessage[]);+ });++ it('waits on every call still pending, in the order they were made', () => {+ const { result } = renderHook(() => useAgentChatPendingToolCalls(), {+ wrapper,+ });++ expect(+ result.current.map((pendingToolCall) => pendingToolCall.toolCallId),+ ).toEqual(['call-1', 'call-2']);+ });++ it('waits on nothing while the turn is still streaming', () => {+ jotaiStore.set(+ agentChatIsStreamingComponentFamilyState.atomFamily(key),+ true,+ );++ const { result } = renderHook(() => useAgentChatPendingToolCalls(), {+ wrapper,+ });++ expect(result.current).toEqual([]);+ });+});diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAnswerAgentChatAsk.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAnswerAgentChatToolCall.test.tsxsimilarity index 83%rename from packages/twenty-front/src/modules/ai/hooks/__tests__/useAnswerAgentChatAsk.test.tsxrename to packages/twenty-front/src/modules/ai/hooks/__tests__/useAnswerAgentChatToolCall.test.tsxindex 6ba392bd3d0..33340f591ac 100644--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAnswerAgentChatAsk.test.tsx+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAnswerAgentChatToolCall.test.tsx@@ -6,7 +6,7 @@ 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 { useAnswerAgentChatToolCall } from '@/ai/hooks/useAnswerAgentChatToolCall';import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';import { agentChatIsAwaitingFirstChunkComponentFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkComponentFamilyState';import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';@@ -49,17 +49,16 @@ const Wrapper = ({ children }: { children: ReactNode }) => (<JotaiProvider store={jotaiStore}>{children}</JotaiProvider>);-const renderAnswerAgentChatAsk = () =>- renderHook(() => useAnswerAgentChatAsk(), { wrapper: Wrapper }).result.current- .answerAgentChatAsk;+const renderAnswerAgentChatToolCall = () =>+ renderHook(() => useAnswerAgentChatToolCall(), { wrapper: Wrapper }).result+ .current.answerAgentChatToolCall;const answer = async () => {- const answerAgentChatAsk = renderAnswerAgentChatAsk();+ const answerAgentChatToolCall = renderAnswerAgentChatToolCall();let isAnswered = false;await act(async () => {- isAnswered = await answerAgentChatAsk({- askId: 'ask-1',+ isAnswered = await answerAgentChatToolCall({toolCallId: 'call-1',response: { answers: [] },optimisticToolOutput: ANSWERED_OUTPUT,@@ -69,7 +68,7 @@ const answer = async () => {return isAnswered;};-describe('useAnswerAgentChatAsk', () => {+describe('useAnswerAgentChatToolCall', () => {beforeEach(() => {jest.clearAllMocks();resetJotaiStore();@@ -91,15 +90,16 @@ describe('useAnswerAgentChatAsk', () => {] 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' } } });+ it('answers the tool call and shows the answer in it right away', async () => {+ mutate.mockResolvedValue({ data: { answerToolCall: { streamId: 's' } } });expect(await answer()).toBe(true);expect(mutate).toHaveBeenCalledWith(expect.objectContaining({variables: {input: {- askId: 'ask-1',+ threadId: 'thread-id',+ toolCallId: 'call-1',response: { answers: [] },modelId: 'model-id',},@@ -112,7 +112,7 @@ describe('useAnswerAgentChatAsk', () => {it('expects no stream when the answer resumes a workflow run', async () => {mutate.mockResolvedValue({- data: { answerAsk: { streamId: null } },+ data: { answerToolCall: { streamId: null } },});await answer();@@ -129,7 +129,7 @@ describe('useAnswerAgentChatAsk', () => {expect(enqueueToast).toHaveBeenCalled();});- it('refetches the conversation instead when the Ask was already answered elsewhere', async () => {+ it('refetches the conversation instead when the call was already answered elsewhere', async () => {const refetchListener = jest.fn();window.addEventListener(AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME,@@ -141,7 +141,7 @@ describe('useAnswerAgentChatAsk', () => {errors: [{message: 'No longer waiting',- extensions: { code: 'ASK_NOT_PENDING' },+ extensions: { code: 'TOOL_CALL_NOT_PENDING' },},],}),diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingAsks.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingAsks.tsdeleted file mode 100644index bf17071bed8..00000000000--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingAsks.ts+++ /dev/null@@ -1,91 +0,0 @@-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 | null;-}): 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',- skip: !isDefined(threadId),- });-- 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,- skip: !isDefined(threadId),- onSseReconnected: refetchPendingInputAsks,- });-- useListenToObjectRecordOperationBrowserEvent({- onObjectRecordOperationBrowserEvent: refetchPendingInputAsks,- objectMetadataItemId: inputAskObjectMetadataItem.id,- enabled: isDefined(threadId),- });-- 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/useAgentChatPendingToolCalls.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingToolCalls.tsnew file mode 100644index 00000000000..3ee10843a55--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingToolCalls.ts@@ -0,0 +1,38 @@+import { useMemo } from 'react';+import { isDefined } from 'twenty-shared/utils';++import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';+import { agentChatIsStreamingComponentFamilyState } from '@/ai/states/agentChatIsStreamingComponentFamilyState';+import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';+import { type AgentChatPendingToolCall } from '@/ai/types/AgentChatPendingToolCall';+import { parsePendingToolCall } from '@/ai/utils/parsePendingToolCall';+import { useAtomComponentFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateValue';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';++// The conversation waits once its turn is over, on every call still pending,+// in the order the agent made them.+export const useAgentChatPendingToolCalls = (): AgentChatPendingToolCall[] => {+ const agentChatDisplayedThread = useAtomStateValue(+ agentChatDisplayedThreadState,+ );+ const agentChatMessages = useAtomComponentFamilyStateValue(+ agentChatMessagesComponentFamilyState,+ { threadId: agentChatDisplayedThread },+ );+ const agentChatIsStreaming = useAtomComponentFamilyStateValue(+ agentChatIsStreamingComponentFamilyState,+ { threadId: agentChatDisplayedThread },+ );++ return useMemo(+ () =>+ agentChatIsStreaming+ ? []+ : agentChatMessages.flatMap((message) =>+ message.parts+ .map(parsePendingToolCall)+ .filter((pendingToolCall) => isDefined(pendingToolCall)),+ ),+ [agentChatMessages, agentChatIsStreaming],+ );+};diff --git a/packages/twenty-front/src/modules/ai/hooks/useAnswerAgentChatAsk.ts b/packages/twenty-front/src/modules/ai/hooks/useAnswerAgentChatToolCall.tssimilarity index 87%rename from packages/twenty-front/src/modules/ai/hooks/useAnswerAgentChatAsk.tsrename to packages/twenty-front/src/modules/ai/hooks/useAnswerAgentChatToolCall.tsindex 1f9cb7d6dff..63e2c35a426 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAnswerAgentChatAsk.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAnswerAgentChatToolCall.ts@@ -6,6 +6,7 @@ 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 { useAgentChatModelId } from '@/ai/hooks/useAgentChatModelId';+import { useAnswerToolCall } from '@/ai/hooks/useAnswerToolCall';import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';import { agentChatErrorComponentFamilyState } from '@/ai/states/agentChatErrorComponentFamilyState';import { agentChatIsAwaitingFirstChunkComponentFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkComponentFamilyState';@@ -17,27 +18,24 @@ 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 { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';-export const useAnswerAgentChatAsk = () => {- const { answerAsk } = useAnswerAsk();+export const useAnswerAgentChatToolCall = () => {+ const { answerToolCall } = useAnswerToolCall();const store = useStore();const { enqueueToast } = useToast();const { modelIdForRequest } = useAgentChatModelId();- // 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(+ // Returns whether the call was answered, so a card can keep itself disabled+ // until the call is closed rather than invite a second answer.+ const answerAgentChatToolCall = useCallback(async ({- askId,toolCallId,response,optimisticToolOutput,}: {- askId: string;toolCallId: string;response: Record<string, unknown>;optimisticToolOutput?: unknown;@@ -80,8 +78,9 @@ export const useAnswerAgentChatAsk = () => {store.set(isAwaitingFirstChunkAtom, true);try {- const { streamId } = await answerAsk({- askId,+ const { streamId } = await answerToolCall({+ threadId,+ toolCallId,response,modelId: modelIdForRequest,});@@ -109,7 +108,9 @@ export const useAnswerAgentChatAsk = () => {);}- if (isGraphqlErrorOfType(error, AiChatErrorCode.ASK_NOT_PENDING)) {+ if (+ isGraphqlErrorOfType(error, AiChatErrorCode.TOOL_CALL_NOT_PENDING)+ ) {dispatchBrowserEvent(AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME);} else if (isDefined(optimisticToolOutput)) {store.set(messagesAtom, (messages) =>@@ -126,8 +127,8 @@ export const useAnswerAgentChatAsk = () => {return false;}},- [answerAsk, store, enqueueToast, modelIdForRequest],+ [answerToolCall, store, enqueueToast, modelIdForRequest],);- return { answerAgentChatAsk };+ return { answerAgentChatToolCall };};diff --git a/packages/twenty-front/src/modules/ai/hooks/useAnswerToolCall.ts b/packages/twenty-front/src/modules/ai/hooks/useAnswerToolCall.tsnew file mode 100644index 00000000000..840120cf3c4--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useAnswerToolCall.ts@@ -0,0 +1,39 @@+import { useCallback } from 'react';++import { ANSWER_TOOL_CALL } from '@/ai/graphql/mutations/answerToolCall';+import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';+import {+ type AnswerToolCallMutation,+ type AnswerToolCallMutationVariables,+} from '~/generated/graphql';++export const useAnswerToolCall = () => {+ const apolloCoreClient = useApolloCoreClient();++ const answerToolCall = useCallback(+ async ({+ threadId,+ toolCallId,+ response,+ modelId,+ }: {+ threadId: string;+ toolCallId: string;+ response: Record<string, unknown>;+ modelId?: string;+ }) => {+ const { data } = await apolloCoreClient.mutate<+ AnswerToolCallMutation,+ AnswerToolCallMutationVariables+ >({+ mutation: ANSWER_TOOL_CALL,+ variables: { input: { threadId, toolCallId, response, modelId } },+ });++ return { streamId: data?.answerToolCall.streamId ?? null };+ },+ [apolloCoreClient],+ );++ return { answerToolCall };+};diff --git a/packages/twenty-front/src/modules/ai/types/AgentChatPendingAsk.ts b/packages/twenty-front/src/modules/ai/types/AgentChatPendingAsk.tsdeleted file mode 100644index c85c4deab71..00000000000--- a/packages/twenty-front/src/modules/ai/types/AgentChatPendingAsk.ts+++ /dev/null@@ -1,8 +0,0 @@-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.tsindex 8d0c07cba2e..9d520112346 100644--- a/packages/twenty-front/src/modules/ai/types/AgentChatPendingQuestion.ts+++ b/packages/twenty-front/src/modules/ai/types/AgentChatPendingQuestion.ts@@ -1,7 +1,6 @@import { type AskQuestionItem } from 'twenty-shared/ai';export type AgentChatPendingQuestion = {- askId: string;toolCallId: string;questions: AskQuestionItem[];};diff --git a/packages/twenty-front/src/modules/ai/types/AgentChatPendingToolCall.ts b/packages/twenty-front/src/modules/ai/types/AgentChatPendingToolCall.tsnew file mode 100644index 00000000000..773687b5421--- /dev/null+++ b/packages/twenty-front/src/modules/ai/types/AgentChatPendingToolCall.ts@@ -0,0 +1,11 @@+import {+ type AskQuestionItem,+ type ProposedEmail,+ type RequestFormField,+} from 'twenty-shared/ai';++export type AgentChatPendingToolCall = { toolCallId: string } & (+ | { kind: 'questions'; questions: AskQuestionItem[] }+ | { kind: 'emailApproval'; email: ProposedEmail }+ | { kind: 'form'; fields: RequestFormField[] }+);diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/parsePendingToolCall.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/parsePendingToolCall.test.tsnew file mode 100644index 00000000000..9a37d554bad--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/parsePendingToolCall.test.ts@@ -0,0 +1,85 @@+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';++import { parsePendingToolCall } from '@/ai/utils/parsePendingToolCall';++const EMAIL = {+ recipients: { to: '[email protected]', cc: '', bcc: '' },+ subject: 'Renewal',+ body: 'Hi Tim',+};++const QUESTIONS = [{ header: 'Plan', question: 'Which plan?', options: [] }];++const FIELDS = [{ name: 'closeDate', label: 'Close date', type: 'DATE' }];++const toolPart = ({+ toolName,+ input,+ status = 'pending',+}: {+ toolName: string;+ input: unknown;+ status?: string;+}) =>+ ({+ type: `tool-${toolName}`,+ toolCallId: 'call-1',+ state: 'output-available',+ input,+ output: { success: true, result: { status } },+ }) as unknown as ExtendedUIMessagePart;++describe('parsePendingToolCall', () => {+ it.each([+ [+ 'questions',+ toolPart({ toolName: 'ask_questions', input: { questions: QUESTIONS } }),+ { toolCallId: 'call-1', kind: 'questions', questions: QUESTIONS },+ ],+ [+ 'an email to review',+ toolPart({ toolName: 'propose_email', input: EMAIL }),+ { toolCallId: 'call-1', kind: 'emailApproval', email: EMAIL },+ ],+ [+ 'a form',+ toolPart({ toolName: 'request_form', input: { fields: FIELDS } }),+ { toolCallId: 'call-1', kind: 'form', fields: FIELDS },+ ],+ ])('reads %s still waiting on an answer', (_description, part, expected) => {+ expect(parsePendingToolCall(part)).toEqual(expected);+ });++ it.each([+ ['a text part', { type: 'text', text: 'Hi' } as ExtendedUIMessagePart],+ [+ 'a call already answered',+ toolPart({+ toolName: 'ask_questions',+ input: { questions: QUESTIONS },+ status: 'answered',+ }),+ ],+ [+ 'a tool that does not pause',+ toolPart({ toolName: 'search_help_center', input: {} }),+ ],+ [+ 'questions without any question',+ toolPart({ toolName: 'ask_questions', input: { questions: [] } }),+ ],+ [+ 'an email without a subject',+ toolPart({+ toolName: 'propose_email',+ input: { ...EMAIL, subject: undefined },+ }),+ ],+ [+ 'a form without fields',+ toolPart({ toolName: 'request_form', input: { fields: [] } }),+ ],+ ])('ignores %s', (_description, part) => {+ expect(parsePendingToolCall(part)).toBeNull();+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/aiChatErrorCode.ts b/packages/twenty-front/src/modules/ai/utils/aiChatErrorCode.tsindex 1b5730c3662..8fd512b43dd 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',- ASK_NOT_PENDING: 'ASK_NOT_PENDING',+ TOOL_CALL_NOT_PENDING: 'TOOL_CALL_NOT_PENDING',QUOTA_EXHAUSTED: 'QUOTA_EXHAUSTED',} as const;diff --git a/packages/twenty-front/src/modules/ai/utils/parsePendingToolCall.ts b/packages/twenty-front/src/modules/ai/utils/parsePendingToolCall.tsnew file mode 100644index 00000000000..609b95c876e--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/parsePendingToolCall.ts@@ -0,0 +1,64 @@+import { isString } from '@sniptt/guards';+import { getToolName, isToolUIPart } from 'ai';+import {+ ASK_QUESTIONS_TOOL_NAME,+ type AskQuestionItem,+ type ExtendedUIMessagePart,+ PROPOSE_EMAIL_TOOL_NAME,+ type ProposedEmail,+ REQUEST_FORM_TOOL_NAME,+ type RequestFormField,+} from 'twenty-shared/ai';+import { isNonEmptyArray, isPlainObject } from 'twenty-shared/utils';++import { type AgentChatPendingToolCall } from '@/ai/types/AgentChatPendingToolCall';++// A call the agent paused on waits until its output says otherwise. The server+// validated its input against the tool's schema when the call was made, so+// only the shape each card needs is checked here.+export const parsePendingToolCall = (+ part: ExtendedUIMessagePart,+): AgentChatPendingToolCall | null => {+ if (+ !isToolUIPart(part) ||+ !isPlainObject(part.output) ||+ !isPlainObject(part.output.result) ||+ part.output.result.status !== 'pending' ||+ !isPlainObject(part.input)+ ) {+ return null;+ }++ const { toolCallId, input } = part;++ switch (getToolName(part)) {+ case ASK_QUESTIONS_TOOL_NAME:+ return Array.isArray(input.questions) && isNonEmptyArray(input.questions)+ ? {+ toolCallId,+ kind: 'questions',+ questions: input.questions as AskQuestionItem[],+ }+ : null;+ case PROPOSE_EMAIL_TOOL_NAME:+ return isPlainObject(input.recipients) &&+ isString(input.subject) &&+ isString(input.body)+ ? {+ toolCallId,+ kind: 'emailApproval',+ email: input as ProposedEmail,+ }+ : null;+ case REQUEST_FORM_TOOL_NAME:+ return Array.isArray(input.fields) && isNonEmptyArray(input.fields)+ ? {+ toolCallId,+ kind: 'form',+ fields: input.fields as RequestFormField[],+ }+ : null;+ default:+ return null;+ }+};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.tsdeleted file mode 100644index ba0b494431c..00000000000--- a/packages/twenty-front/src/modules/input-ask/graphql/mutations/answerAsk.ts+++ /dev/null@@ -1,9 +0,0 @@-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.tsdeleted file mode 100644index eb6fb93bef9..00000000000--- a/packages/twenty-front/src/modules/input-ask/hooks/useAnswerAsk.ts+++ /dev/null@@ -1,37 +0,0 @@-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.tsdeleted file mode 100644index dae1a58aaee..00000000000--- a/packages/twenty-front/src/modules/input-ask/utils/__tests__/parseInputAskForm.test.ts+++ /dev/null@@ -1,35 +0,0 @@-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.tsdeleted file mode 100644index 7f0f332102a..00000000000--- a/packages/twenty-front/src/modules/input-ask/utils/parseInputAskForm.ts+++ /dev/null@@ -1,30 +0,0 @@-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.tsxindex 03fdeba114e..17cafb23b9b 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,23 +1,14 @@-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 { WorkflowFormStepAskSubmitButton } from '@/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormStepAskSubmitButton';+import { WorkflowFormFields } from '@/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFields';+import { WorkflowFormStepSubmitButton } from '@/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormStepSubmitButton';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';@@ -34,34 +25,21 @@ export const WorkflowEditActionFormFiller = ({action,actionOptions,}: WorkflowEditActionFormFillerProps) => {- const { t } = useLingui();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);- const onFieldUpdate = ({- fieldId,- value,- }: {- fieldId: string;- value: unknown;- }) => {+ const onFieldUpdate = (fieldName: string, value: unknown) => {if (actionOptions.readonly === true) {return;}const updatedFormData = formData.map((field) =>- field.id === fieldId ? { ...field, value } : field,+ field.name === fieldName ? { ...field, value } : field,);setFormData(updatedFormData);@@ -101,90 +79,24 @@ export const WorkflowEditActionFormFiller = ({<><WorkflowRunSSESubscribeEffect workflowRunId={workflowRunId} /><WorkflowStepBody>- {formData.map((field) => {- if (field.type === 'RECORD') {- const objectNameSingular = field.settings?.objectName;-- if (!isDefined(objectNameSingular)) {- return null;- }-- return (- <FormSingleRecordPicker- key={field.id}- label={field.label}- defaultValue={field.value?.id}- onChange={(recordId) => {- onFieldUpdate({ fieldId: field.id, value: { id: recordId } });- }}- objectNameSingulars={[objectNameSingular]}- disabled={actionOptions.readonly}- />- );- }-- if (field.type === 'SELECT' || field.type === 'MULTI_SELECT') {- const selectedFieldId = field.settings?.selectedFieldId;-- if (!isDefined(selectedFieldId)) {- return null;- }-- return (- <WorkflowFormFieldInput- key={field.id}- fieldMetadataId={selectedFieldId}- defaultValue={field.value}- readonly={actionOptions.readonly}- onChange={(value) => {- onFieldUpdate({ fieldId: field.id, value });- }}- />- );- }-- return (- <FormFieldInput- key={field.id}- field={{- label: field.label,- type: field.type,- metadata: {} as FieldMetadata,- }}- onChange={(value) => {- onFieldUpdate({ fieldId: field.id, value });- }}- defaultValue={field.value}- readonly={actionOptions.readonly}- placeholder={- field.placeholder ??- getDefaultFormFieldSettings(field.type).placeholder- }- onError={setError}- />- );- })}+ <WorkflowFormFields+ fields={formData}+ readonly={actionOptions.readonly}+ onChange={onFieldUpdate}+ onError={setError}+ /></WorkflowStepBody>{!actionOptions.readonly && (<SidePanelFooteractions={[- isDefined(inputAskObjectMetadataItem) ? (- <WorkflowFormStepAskSubmitButton- key="submit"- workflowRunId={workflowRunId}- stepId={action.id}- disabled={!canSubmit}- getResponse={getResponse}- onSubmitted={goBackFromSidePanel}- />- ) : (- <WorkflowStepCmdEnterButton- key="submit"- title={t`Submit`}- onClick={() => {}}- disabled- />- ),+ <WorkflowFormStepSubmitButton+ key="submit"+ workflowRunId={workflowRunId}+ stepId={action.id}+ disabled={!canSubmit}+ getResponse={getResponse}+ onSubmitted={goBackFromSidePanel}+ />,]}/>)}diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFields.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFields.tsxnew file mode 100644index 00000000000..c5372739f3c--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFields.tsx@@ -0,0 +1,89 @@+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 { WorkflowFormFieldInput } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowFormFieldInput';+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 { isDefined } from 'twenty-shared/utils';++type WorkflowFormFieldsProps = {+ fields: Omit<WorkflowFormActionField, 'id'>[];+ readonly: boolean;+ onChange: (fieldName: string, value: unknown) => void;+ onError?: (error: string | undefined) => void;+};++// The fields a person fills in to answer a form, whether a workflow form step+// or an agent asked for it.+export const WorkflowFormFields = ({+ fields,+ readonly,+ onChange,+ onError,+}: WorkflowFormFieldsProps) => (+ <>+ {fields.map((field) => {+ if (field.type === 'RECORD') {+ const objectNameSingular = field.settings?.objectName;++ if (!isDefined(objectNameSingular)) {+ return null;+ }++ return (+ <FormSingleRecordPicker+ key={field.name}+ label={field.label}+ defaultValue={field.value?.id}+ onChange={(recordId) => {+ onChange(field.name, { id: recordId });+ }}+ objectNameSingulars={[objectNameSingular]}+ disabled={readonly}+ />+ );+ }++ if (field.type === 'SELECT' || field.type === 'MULTI_SELECT') {+ const selectedFieldId = field.settings?.selectedFieldId;++ if (!isDefined(selectedFieldId)) {+ return null;+ }++ return (+ <WorkflowFormFieldInput+ key={field.name}+ fieldMetadataId={selectedFieldId}+ defaultValue={field.value}+ readonly={readonly}+ onChange={(value) => {+ onChange(field.name, value);+ }}+ />+ );+ }++ return (+ <FormFieldInput+ key={field.name}+ field={{+ label: field.label,+ type: field.type,+ metadata: {} as FieldMetadata,+ }}+ onChange={(value) => {+ onChange(field.name, value);+ }}+ defaultValue={field.value}+ readonly={readonly}+ placeholder={+ field.placeholder ??+ getDefaultFormFieldSettings(field.type).placeholder+ }+ onError={onError}+ />+ );+ })}+ </>+);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/WorkflowFormStepSubmitButton.tsxsimilarity index 77%rename from packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormStepAskSubmitButton.tsxrename to packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormStepSubmitButton.tsxindex a298515f9af..e3036fdeda2 100644--- 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/WorkflowFormStepSubmitButton.tsx@@ -1,11 +1,11 @@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 { useAnswerFormStep } from '@/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStep';import { useLingui } from '@lingui/react/macro';import { useState } from 'react';import { useToast } from 'twenty-ui/components';-type WorkflowFormStepAskSubmitButtonProps = {+type WorkflowFormStepSubmitButtonProps = {workflowRunId: string;stepId: string;disabled: boolean;@@ -13,16 +13,16 @@ type WorkflowFormStepAskSubmitButtonProps = {onSubmitted: () => void;};-export const WorkflowFormStepAskSubmitButton = ({+export const WorkflowFormStepSubmitButton = ({workflowRunId,stepId,disabled,getResponse,onSubmitted,-}: WorkflowFormStepAskSubmitButtonProps) => {+}: WorkflowFormStepSubmitButtonProps) => {const { t } = useLingui();const { enqueueToast } = useToast();- const { answerFormStepAsk } = useAnswerFormStepAsk({+ const { answerFormStep } = useAnswerFormStep({workflowRunId,stepId,});@@ -36,7 +36,7 @@ export const WorkflowFormStepAskSubmitButton = ({setIsSubmitting(true);try {- const isSubmitted = await answerFormStepAsk(await getResponse());+ const isSubmitted = await answerFormStep(await getResponse());if (isSubmitted) {onSubmitted();diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStep.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStep.tsnew file mode 100644index 00000000000..3e2a9eaf9c8--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStep.ts@@ -0,0 +1,72 @@+import { CoreObjectNameSingular } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { useAnswerToolCall } from '@/ai/hooks/useAnswerToolCall';+import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';+import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';+import { useFindOneRecordQuery } from '@/object-record/hooks/useFindOneRecordQuery';+import { useWorkflowRun } from '@/workflow/hooks/useWorkflowRun';+import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';++export const useAnswerFormStep = ({+ workflowRunId,+ stepId,+}: {+ workflowRunId: string;+ stepId: string;+}) => {+ const apolloCoreClient = useApolloCoreClient();+ const workflowRun = useWorkflowRun({ workflowRunId });+ const { answerToolCall } = useAnswerToolCall();++ const { findOneRecordQuery: findOneWorkflowRunQuery } = useFindOneRecordQuery(+ {+ objectNameSingular: CoreObjectNameSingular.WorkflowRun,+ recordGqlFields: {+ id: true,+ name: true,+ status: true,+ startedAt: true,+ endedAt: true,+ },+ },+ );++ const refetchWorkflowRun = () =>+ apolloCoreClient.query({+ query: findOneWorkflowRunQuery,+ variables: { objectRecordId: workflowRunId },+ fetchPolicy: 'network-only',+ });++ // A form step's call is named after the step, in the conversation its+ // current execution recorded. Returns false when the form no longer waits:+ // it has no conversation, or someone answered it or the run ended first.+ const answerFormStep = async (+ response: Record<string, unknown>,+ ): Promise<boolean> => {+ const threadId = workflowRun?.state?.stepInfos[stepId]?.threadId;++ if (!isDefined(threadId)) {+ return false;+ }++ try {+ await answerToolCall({ threadId, toolCallId: stepId, response });+ } catch (error) {+ if (!isGraphqlErrorOfType(error, AiChatErrorCode.TOOL_CALL_NOT_PENDING)) {+ throw error;+ }++ await refetchWorkflowRun();++ return false;+ }++ await refetchWorkflowRun();++ return true;+ };++ return { answerFormStep };+};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.tsdeleted file mode 100644index fb804bf3fa6..00000000000--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStepAsk.ts+++ /dev/null@@ -1,76 +0,0 @@-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-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.tsindex 248161b31e7..6272aacb403 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@@ -1186,6 +1186,7 @@ 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.tsindex 919c56c2a30..c7c2f18e1f5 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@@ -14,12 +14,11 @@ import { AddWorkflowRunToChatThreadsCommand } from 'src/database/commands/upgradimport { SyncDeactivateWorkflowAvailabilityCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607920000-sync-deactivate-workflow-availability.command';import { RemoveAddNodeWorkflowCommandMenuItemCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607921000-remove-add-node-workflow-command-menu-item.command';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 { MoveAgentChatThreadsToRecordModelCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790751626421-move-agent-chat-threads-to-record-model.command';import { AddChatRecordPageCommandMenuItemsCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790751626422-add-chat-record-page-command-menu-items.command';-import { OpenAsksForPendingInputCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790714482317-open-asks-for-pending-input.command';import { AddChatRecordPageCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790756589463-add-chat-record-page.command';+import { RecordPendingFormConversationsCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790772993322-record-pending-form-conversations.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';@@ -43,12 +42,11 @@ import { WorkspaceMigrationRunnerModule } from 'src/engine/workspace-manager/worRemoveAddNodeWorkflowCommandMenuItemCommand,SyncShortLinkObjectCommand,OpenAgentChatThreadArchivedAtWritabilityCommand,- AddInputAskObjectCommand,GateConversationsWidgetOnFeatureFlagCommand,MoveAgentChatThreadsToRecordModelCommand,AddChatRecordPageCommandMenuItemsCommand,AddChatRecordPageCommand,- OpenAsksForPendingInputCommand,+ RecordPendingFormConversationsCommand,],})export class V2_44_UpgradeVersionCommandModule {}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790681093095-add-input-ask-object.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790681093095-add-input-ask-object.command.tsdeleted file mode 100644index 6795e575773..00000000000--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790681093095-add-input-ask-object.command.ts+++ /dev/null@@ -1,296 +0,0 @@-import { Command } from 'nest-commander';-import { STANDARD_OBJECTS } from 'twenty-shared/metadata';-import { isDefined } from 'twenty-shared/utils';--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 { getStandardFlatEntitiesToCreateOrThrow } from 'src/database/commands/upgrade-version-command/2-10/utils/get-standard-flat-entities-to-create-or-throw.util';-import { collectInputAskStandardUniversalIdentifiers } from 'src/database/commands/upgrade-version-command/2-44/utils/collect-input-ask-standard-universal-identifiers.util';-import { ApplicationService } from 'src/engine/core-modules/application/application.service';-import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';-import { type SyncableFlatEntity } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-from.type';-import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';-import { computeTwentyStandardApplicationAllFlatEntityMaps } from 'src/engine/workspace-manager/twenty-standard-application/utils/twenty-standard-application-all-flat-entity-maps.constant';-import { WorkspaceMigrationBuilderException } from 'src/engine/workspace-manager/workspace-migration/exceptions/workspace-migration-builder-exception';-import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';--const buildCreationOperations = <TFlatEntity extends SyncableFlatEntity>({- standardFlatEntityMaps,- existingFlatEntityMaps,- universalIdentifiers,-}: {- standardFlatEntityMaps: FlatEntityMaps<TFlatEntity>;- existingFlatEntityMaps: FlatEntityMaps<TFlatEntity>;- universalIdentifiers: string[];-}) => ({- flatEntityToCreate: getStandardFlatEntitiesToCreateOrThrow({- standardFlatEntityMaps,- existingFlatEntityMaps,- universalIdentifiers,- }),- flatEntityToDelete: [],- flatEntityToUpdate: [],-});--@RegisteredWorkspaceCommand('2.44.0', 1790681093095)-@Command({- name: 'upgrade:2-44:add-input-ask-object',- description: 'Create the inputAsk standard object in existing workspaces',-})-export class AddInputAskObjectCommand extends ProvisionedWorkspaceCommandRunner {- constructor(- protected readonly workspaceIteratorService: WorkspaceIteratorService,- private readonly applicationService: ApplicationService,- private readonly workspaceCacheService: WorkspaceCacheService,- private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,- ) {- super(workspaceIteratorService);- }-- override async runOnWorkspace(args: RunOnWorkspaceArgs): Promise<void> {- await this.up(args);- }-- async up({ workspaceId, options }: RunOnWorkspaceArgs): Promise<void> {- const isDryRun = options.dryRun ?? false;- const {- flatObjectMetadataMaps,- flatFieldMetadataMaps,- flatIndexMaps,- flatSearchFieldMetadataMaps,- flatViewMaps,- flatViewFieldMaps,- } = await this.workspaceCacheService.getOrRecompute(workspaceId, [- 'flatObjectMetadataMaps',- 'flatFieldMetadataMaps',- 'flatIndexMaps',- 'flatSearchFieldMetadataMaps',- 'flatViewMaps',- 'flatViewFieldMaps',- ]);-- // The inverse relation fields land on these objects, so creating inputAsk- // before they exist would build a relation with no other side.- const missingRelationTarget = [- STANDARD_OBJECTS.workflowRun,- STANDARD_OBJECTS.workspaceMember,- STANDARD_OBJECTS.agentChatThread,- ].find(- ({ universalIdentifier }) =>- !isDefined(- flatObjectMetadataMaps.byUniversalIdentifier[universalIdentifier],- ),- );-- if (isDefined(missingRelationTarget)) {- this.logger.warn(- `Relation target object not found for workspace ${workspaceId}, skipping inputAsk object sync`,- );-- return;- }-- const { twentyStandardFlatApplication } =- await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(- { workspaceId },- );- const { allFlatEntityMaps: standardAllFlatEntityMaps } =- computeTwentyStandardApplicationAllFlatEntityMaps({- now: new Date().toISOString(),- workspaceId,- twentyStandardApplicationId: twentyStandardFlatApplication.id,- });- const universalIdentifiers = collectInputAskStandardUniversalIdentifiers({- standardAllFlatEntityMaps,- });- const allFlatEntityOperationByMetadataName = {- objectMetadata: buildCreationOperations({- standardFlatEntityMaps: standardAllFlatEntityMaps.flatObjectMetadataMaps,- existingFlatEntityMaps: flatObjectMetadataMaps,- universalIdentifiers: universalIdentifiers.objectMetadata,- }),- fieldMetadata: buildCreationOperations({- standardFlatEntityMaps: standardAllFlatEntityMaps.flatFieldMetadataMaps,- existingFlatEntityMaps: flatFieldMetadataMaps,- universalIdentifiers: universalIdentifiers.fieldMetadata,- }),- index: buildCreationOperations({- standardFlatEntityMaps: standardAllFlatEntityMaps.flatIndexMaps,- existingFlatEntityMaps: flatIndexMaps,- universalIdentifiers: universalIdentifiers.index,- }),- searchFieldMetadata: buildCreationOperations({- standardFlatEntityMaps: standardAllFlatEntityMaps.flatSearchFieldMetadataMaps,- existingFlatEntityMaps: flatSearchFieldMetadataMaps,- universalIdentifiers: universalIdentifiers.searchFieldMetadata,- }),- view: buildCreationOperations({- standardFlatEntityMaps: standardAllFlatEntityMaps.flatViewMaps,- existingFlatEntityMaps: flatViewMaps,- universalIdentifiers: universalIdentifiers.view,- }),- viewField: buildCreationOperations({- standardFlatEntityMaps: standardAllFlatEntityMaps.flatViewFieldMaps,- existingFlatEntityMaps: flatViewFieldMaps,- universalIdentifiers: universalIdentifiers.viewField,- }),- };- const totalOperationCount = Object.values(- allFlatEntityOperationByMetadataName,- ).reduce(- (total, operations) => total + operations.flatEntityToCreate.length,- 0,- );-- if (totalOperationCount === 0) {- this.logger.log(- `inputAsk standard metadata already exists for workspace ${workspaceId}, skipping`,- );-- return;- }-- const creationSummary = `${allFlatEntityOperationByMetadataName.objectMetadata.flatEntityToCreate.length} inputAsk object(s), ${allFlatEntityOperationByMetadataName.fieldMetadata.flatEntityToCreate.length} field(s), ${allFlatEntityOperationByMetadataName.index.flatEntityToCreate.length} index(es) and ${allFlatEntityOperationByMetadataName.view.flatEntityToCreate.length} view(s)`;-- if (isDryRun) {- this.logger.log(- `[DRY RUN] Would create ${creationSummary} for workspace ${workspaceId}`,- );-- return;- }-- const result =- await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunLegacyWorkspaceMigration(- {- allFlatEntityOperationByMetadataName,- workspaceId,- isSystemBuild: true,- applicationUniversalIdentifier:- twentyStandardFlatApplication.universalIdentifier,- },- );-- if (result.status === 'fail') {- throw new WorkspaceMigrationBuilderException(- result,- `Failed to create the inputAsk object for workspace ${workspaceId}`,- );- }-- this.logger.log(`Created ${creationSummary} for workspace ${workspaceId}`);- }-- async down({ workspaceId }: RunOnWorkspaceArgs): Promise<void> {- const {- flatObjectMetadataMaps,- flatFieldMetadataMaps,- flatViewMaps,- flatViewFieldGroupMaps,- flatViewFieldMaps,- flatViewFilterMaps,- } = await this.workspaceCacheService.getOrRecompute(workspaceId, [- 'flatViewFilterMaps',- 'flatObjectMetadataMaps',- 'flatFieldMetadataMaps',- 'flatViewMaps',- 'flatViewFieldGroupMaps',- 'flatViewFieldMaps',- ]);- const inputAskObject =- flatObjectMetadataMaps.byUniversalIdentifier[- STANDARD_OBJECTS.inputAsk.universalIdentifier- ];-- if (!isDefined(inputAskObject)) {- return;- }-- const { twentyStandardFlatApplication } =- await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(- { workspaceId },- );-- // Deleting the object takes its own fields along; the inverse sides on- // the other objects have to be named.- const inverseFields = [- STANDARD_OBJECTS.workflowRun.fields.inputAsks,- STANDARD_OBJECTS.workspaceMember.fields.inputAsks,- STANDARD_OBJECTS.agentChatThread.fields.inputAsks,- ]- .map(- ({ universalIdentifier }) =>- flatFieldMetadataMaps.byUniversalIdentifier[universalIdentifier],- )- .filter(isDefined);-- // Named explicitly too: a cascade in the database would leave them in- // the cached maps, and a later up would take them as already there.- const views = Object.values(flatViewMaps.byUniversalIdentifier)- .filter(isDefined)- .filter((view) => view.objectMetadataId === inputAskObject.id);- const viewIds = new Set(views.map(({ id }) => id));- const viewFieldGroups = Object.values(- flatViewFieldGroupMaps.byUniversalIdentifier,- )- .filter(isDefined)- .filter(({ viewId }) => viewIds.has(viewId));- const viewFields = Object.values(flatViewFieldMaps.byUniversalIdentifier)- .filter(isDefined)- .filter(({ viewId }) => viewIds.has(viewId));- const viewFilters = Object.values(flatViewFilterMaps.byUniversalIdentifier)- .filter(isDefined)- .filter(({ viewId }) => viewIds.has(viewId));-- const result =- await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunLegacyWorkspaceMigration(- {- allFlatEntityOperationByMetadataName: {- objectMetadata: {- flatEntityToCreate: [],- flatEntityToDelete: [inputAskObject],- flatEntityToUpdate: [],- },- view: {- flatEntityToCreate: [],- flatEntityToDelete: views,- flatEntityToUpdate: [],- },- viewFieldGroup: {- flatEntityToCreate: [],- flatEntityToDelete: viewFieldGroups,- flatEntityToUpdate: [],- },- viewField: {- flatEntityToCreate: [],- flatEntityToDelete: viewFields,- flatEntityToUpdate: [],- },- viewFilter: {- flatEntityToCreate: [],- flatEntityToDelete: viewFilters,- flatEntityToUpdate: [],- },- fieldMetadata: {- flatEntityToCreate: [],- flatEntityToDelete: inverseFields,- flatEntityToUpdate: [],- },- },- workspaceId,- isSystemBuild: true,- applicationUniversalIdentifier:- twentyStandardFlatApplication.universalIdentifier,- },- );-- if (result.status === 'fail') {- throw new WorkspaceMigrationBuilderException(- result,- `Failed to remove the inputAsk object for workspace ${workspaceId}`,- );- }- }-}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.tsdeleted file mode 100644index 8a547840579..00000000000--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790714482317-open-asks-for-pending-input.command.ts+++ /dev/null@@ -1,412 +0,0 @@-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, MoreThan, 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';--const WORKFLOW_RUN_BATCH_SIZE = 100;--const MIN_UUID = '00000000-0000-0000-0000-000000000000';--type PendingFormStepWorkflowRun = Pick<- WorkflowRunWorkspaceEntity,- 'id' | 'state' | 'createdBy'->;--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 },- );-- let openedCount = 0;- let cursor = MIN_UUID;-- while (true) {- // Only a running run accepts a submission. Paged with only the columns- // read: a run's stepLogs can be large and a workspace can hold many runs- // stuck in RUNNING.- const workflowRuns: PendingFormStepWorkflowRun[] =- await workflowRunRepository.find({- where: { status: WorkflowRunStatus.RUNNING, id: MoreThan(cursor) },- select: [- 'id',- 'state',- 'createdBySource',- 'createdByWorkspaceMemberId',- ],- order: { id: 'ASC' },- take: WORKFLOW_RUN_BATCH_SIZE,- });-- if (workflowRuns.length === 0) {- return openedCount;- }-- cursor = workflowRuns[workflowRuns.length - 1].id;-- for (const workflowRun of workflowRuns) {- openedCount += await this.openAsksForWorkflowRunFormSteps({- workflowRun,- isDryRun,- });- }- }- }-- private async openAsksForWorkflowRunFormSteps({- workflowRun,- isDryRun,- }: {- workflowRun: PendingFormStepWorkflowRun;- isDryRun: boolean;- }): Promise<number> {- const inputAskRepository =- this.workspaceOrmManager.getRepository<InputAskWorkspaceEntity>(- 'inputAsk',- { shouldBypassPermissionChecks: true },- );-- const stepInfos = workflowRun.state?.stepInfos ?? {};-- let openedCount = 0;-- 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;- }-- if (isDryRun) {- openedCount++;- continue;- }-- const lowestPosition = await inputAskRepository.minimum('position');-- try {- 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,- });- } catch (error) {- // An Ask opened for the same step in the meantime is the one wanted.- if (- error instanceof TwentyOrmException &&- error.code === TwentyOrmExceptionCode.DUPLICATE_ENTRY_DETECTED- ) {- continue;- }-- throw error;- }-- openedCount++;- }-- 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/2-44-workspace-command-1790772993322-record-pending-form-conversations.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790772993322-record-pending-form-conversations.command.tsnew file mode 100644index 00000000000..fc9eeab4320--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790772993322-record-pending-form-conversations.command.ts@@ -0,0 +1,191 @@+import { randomUUID } from 'node:crypto';++import { Command } from 'nest-commander';+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';+import { isDefined } from 'twenty-shared/utils';+import { StepStatus, WorkflowActionType } from 'twenty-shared/workflow';++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 { 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 { type AgentTurnWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-turn.workspace-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 { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';+import {+ WorkflowRunStatus,+ type WorkflowRunWorkspaceEntity,+} from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';++const REQUEST_FORM_TOOL_NAME = 'request_form';++// A form step is answered in its conversation, as a request_form call named+// after the step that the conversation waits on. A form step waiting since+// before this release has none, so each one still waiting gets the+// conversation its step now records.+@RegisteredWorkspaceCommand('2.44.0', 1790772993322)+@Command({+ name: 'upgrade:2-44:record-pending-form-conversations',+ description:+ 'Record the conversation each form step waiting before this release is answered in',+})+export class RecordPendingFormConversationsCommand 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 { flatFieldMetadataMaps } =+ await this.workspaceCacheService.getOrRecompute(workspaceId, [+ 'flatFieldMetadataMaps',+ ]);++ if (+ !isDefined(+ flatFieldMetadataMaps.byUniversalIdentifier[+ STANDARD_OBJECTS.agentChatThread.fields.workflowRun+ .universalIdentifier+ ],+ )+ ) {+ this.logger.log(+ `Conversations cannot name a workflow run in workspace ${workspaceId}, skipping`,+ );++ return;+ }++ const isDryRun = options.dryRun ?? false;++ // The history fence: its tables cannot move while the forms are recorded.+ const recordedCount = await this.storage.run(workspaceId, () =>+ this.workspaceOrmManager.executeInWorkspaceContext(+ () => this.recordPendingFormConversations({ isDryRun }),+ buildSystemAuthContext(workspaceId),+ ),+ );++ this.logger.log(+ `${isDryRun ? '[DRY RUN] Would record' : 'Recorded'} ${recordedCount} conversation(s) for pending form steps in workspace ${workspaceId}`,+ );+ }++ async down(_args: RunOnWorkspaceArgs): Promise<void> {+ // The recorded conversations are where these forms are answered from now+ // on, so they are left in place.+ }++ private async recordPendingFormConversations({+ isDryRun,+ }: {+ isDryRun: boolean;+ }): Promise<number> {+ const getRepository = <TEntity extends object>(objectName: string) =>+ this.workspaceOrmManager.getRepository<TEntity>(objectName, {+ shouldBypassPermissionChecks: true,+ });+ const workflowRunRepository =+ getRepository<WorkflowRunWorkspaceEntity>('workflowRun');+ const threadRepository =+ getRepository<AgentChatThreadWorkspaceEntity>('agentChatThread');+ const turnRepository = getRepository<AgentTurnWorkspaceEntity>('agentTurn');+ const messageRepository =+ getRepository<AgentMessageWorkspaceEntity>('agentMessage');+ const messagePartRepository =+ getRepository<AgentMessagePartWorkspaceEntity>('agentMessagePart');++ // Only a running run accepts a submission.+ const workflowRuns = await workflowRunRepository.find({+ where: { status: WorkflowRunStatus.RUNNING },+ select: { id: true, state: true },+ });++ let recordedCount = 0;++ for (const workflowRun of workflowRuns) {+ const stepInfos = { ...workflowRun.state?.stepInfos };+ let hasRecordedConversation = false;++ for (const step of workflowRun.state?.flow?.steps ?? []) {+ const stepInfo = stepInfos[step.id];++ if (+ step.type !== WorkflowActionType.FORM ||+ stepInfo?.status !== StepStatus.PENDING ||+ isDefined(stepInfo.error) ||+ isDefined(stepInfo.threadId)+ ) {+ continue;+ }++ recordedCount++;++ if (isDryRun) {+ continue;+ }++ const threadId = randomUUID();+ const turnId = randomUUID();+ const messageId = randomUUID();++ await threadRepository.insert({+ id: threadId,+ title: step.name,+ workflowRunId: workflowRun.id,+ });+ await turnRepository.insert({ id: turnId, threadId });+ await messageRepository.insert({+ id: messageId,+ threadId,+ turnId,+ role: AgentMessageRole.ASSISTANT,+ processedAt: new Date().toISOString(),+ });+ await messagePartRepository.insert({+ messageId,+ orderIndex: 0,+ type: `tool-${REQUEST_FORM_TOOL_NAME}`,+ toolName: REQUEST_FORM_TOOL_NAME,+ toolCallId: step.id,+ toolInput: { fields: step.settings.input },+ toolOutput: {+ success: true,+ message: 'Form presented to the user; awaiting their answer.',+ result: { status: 'pending' },+ },+ state: 'output-available',+ });+ await threadRepository.update(+ { id: threadId },+ { pendingQuestionMessageId: messageId },+ );++ stepInfos[step.id] = { ...stepInfo, threadId };+ hasRecordedConversation = true;+ }++ if (hasRecordedConversation) {+ await workflowRunRepository.update(workflowRun.id, {+ state: { ...workflowRun.state, stepInfos },+ });+ }+ }++ return recordedCount;+ }+}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/__tests__/collect-input-ask-standard-universal-identifiers.util.spec.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/__tests__/collect-input-ask-standard-universal-identifiers.util.spec.tsdeleted file mode 100644index ca203868ee5..00000000000--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/__tests__/collect-input-ask-standard-universal-identifiers.util.spec.ts+++ /dev/null@@ -1,87 +0,0 @@-import { STANDARD_OBJECTS } from 'twenty-shared/metadata';-import { isDefined } from 'twenty-shared/utils';-import { v4 } from 'uuid';--import { collectInputAskStandardUniversalIdentifiers } from 'src/database/commands/upgrade-version-command/2-44/utils/collect-input-ask-standard-universal-identifiers.util';-import { computeTwentyStandardApplicationAllFlatEntityMaps } from 'src/engine/workspace-manager/twenty-standard-application/utils/twenty-standard-application-all-flat-entity-maps.constant';--describe('collectInputAskStandardUniversalIdentifiers', () => {- const { allFlatEntityMaps: standardAllFlatEntityMaps } =- computeTwentyStandardApplicationAllFlatEntityMaps({- now: new Date().toISOString(),- workspaceId: v4(),- twentyStandardApplicationId: v4(),- });-- const universalIdentifiers = collectInputAskStandardUniversalIdentifiers({- standardAllFlatEntityMaps,- });-- it('should collect the inputAsk standard object only', () => {- expect(universalIdentifiers.objectMetadata).toEqual([- STANDARD_OBJECTS.inputAsk.universalIdentifier,- ]);- });-- it('should collect every inputAsk field declared in twenty-shared', () => {- const declaredFieldUniversalIdentifiers = Object.values(- STANDARD_OBJECTS.inputAsk.fields,- ).map(({ universalIdentifier }) => universalIdentifier);-- expect(universalIdentifiers.fieldMetadata).toEqual(- expect.arrayContaining(declaredFieldUniversalIdentifiers),- );- });-- it('should collect the inverse relation fields living on the other objects', () => {- expect(universalIdentifiers.fieldMetadata).toEqual(- expect.arrayContaining([- STANDARD_OBJECTS.workflowRun.fields.inputAsks.universalIdentifier,- STANDARD_OBJECTS.workspaceMember.fields.inputAsks.universalIdentifier,- STANDARD_OBJECTS.agentChatThread.fields.inputAsks.universalIdentifier,- ]),- );- });-- it('should collect every inputAsk index declared in twenty-shared', () => {- const declaredIndexUniversalIdentifiers = Object.values(- STANDARD_OBJECTS.inputAsk.indexes,- ).map(({ universalIdentifier }) => universalIdentifier);-- expect(universalIdentifiers.index).toEqual(- expect.arrayContaining(declaredIndexUniversalIdentifiers),- );- });-- it('should collect every inputAsk view declared in twenty-shared', () => {- const declaredViewUniversalIdentifiers = Object.values(- STANDARD_OBJECTS.inputAsk.views,- ).map(({ universalIdentifier }) => universalIdentifier);-- expect(universalIdentifiers.view).toHaveLength(- declaredViewUniversalIdentifiers.length,- );- expect(universalIdentifiers.view).toEqual(- expect.arrayContaining(declaredViewUniversalIdentifiers),- );- expect(universalIdentifiers.viewField.length).toBeGreaterThan(0);- });-- it('should not collect metadata belonging to unrelated standard objects', () => {- const companyFieldUniversalIdentifiers = Object.values(- standardAllFlatEntityMaps.flatFieldMetadataMaps.byUniversalIdentifier,- )- .filter(isDefined)- .filter(- (flatFieldMetadata) =>- flatFieldMetadata.objectMetadataUniversalIdentifier ===- STANDARD_OBJECTS.company.universalIdentifier,- )- .map((flatFieldMetadata) => flatFieldMetadata.universalIdentifier);-- expect(companyFieldUniversalIdentifiers.length).toBeGreaterThan(0);- expect(universalIdentifiers.fieldMetadata).toEqual(- expect.not.arrayContaining(companyFieldUniversalIdentifiers),- );- });-});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.tsdeleted file mode 100644index 64fa348e43a..00000000000--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/__tests__/find-pending-ask-questions-part.util.spec.ts+++ /dev/null@@ -1,36 +0,0 @@-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/collect-input-ask-standard-universal-identifiers.util.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/collect-input-ask-standard-universal-identifiers.util.tsdeleted file mode 100644index 5b213f7f267..00000000000--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/collect-input-ask-standard-universal-identifiers.util.ts+++ /dev/null@@ -1,65 +0,0 @@-import { STANDARD_OBJECTS } from 'twenty-shared/metadata';-import { isDefined } from 'twenty-shared/utils';--import { type SyncableFlatEntity } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-from.type';-import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';-import { type TwentyStandardAllFlatEntityMaps } from 'src/engine/workspace-manager/twenty-standard-application/types/twenty-standard-all-flat-entity-maps.type';--const INPUT_ASK_OBJECT_UNIVERSAL_IDENTIFIER =- STANDARD_OBJECTS.inputAsk.universalIdentifier;--const collectUniversalIdentifiers = <TFlatEntity extends SyncableFlatEntity>(- flatEntityMaps: FlatEntityMaps<TFlatEntity>,- isInputAskEntity: (flatEntity: NoInfer<TFlatEntity>) => boolean,-) =>- Object.values(flatEntityMaps.byUniversalIdentifier)- .filter(isDefined)- .filter(isInputAskEntity)- .map(({ universalIdentifier }) => universalIdentifier);--const isOnInputAsk = ({- objectMetadataUniversalIdentifier,-}: {- objectMetadataUniversalIdentifier: string | null;-}) =>- objectMetadataUniversalIdentifier === INPUT_ASK_OBJECT_UNIVERSAL_IDENTIFIER;--export const collectInputAskStandardUniversalIdentifiers = ({- standardAllFlatEntityMaps,-}: {- standardAllFlatEntityMaps: TwentyStandardAllFlatEntityMaps;-}) => {- const view = collectUniversalIdentifiers(- standardAllFlatEntityMaps.flatViewMaps,- isOnInputAsk,- );- const viewUniversalIdentifiers = new Set(view);-- return {- objectMetadata: [INPUT_ASK_OBJECT_UNIVERSAL_IDENTIFIER],- // The inverse sides of inputAsk's relations live on workflowRun,- // agentChatThread and workspaceMember; filtering on the owning object alone- // would create each relation half-built.- fieldMetadata: collectUniversalIdentifiers(- standardAllFlatEntityMaps.flatFieldMetadataMaps,- (flatFieldMetadata) =>- isOnInputAsk(flatFieldMetadata) ||- flatFieldMetadata.relationTargetObjectMetadataUniversalIdentifier ===- INPUT_ASK_OBJECT_UNIVERSAL_IDENTIFIER,- ),- index: collectUniversalIdentifiers(- standardAllFlatEntityMaps.flatIndexMaps,- isOnInputAsk,- ),- searchFieldMetadata: collectUniversalIdentifiers(- standardAllFlatEntityMaps.flatSearchFieldMetadataMaps,- isOnInputAsk,- ),- view,- viewField: collectUniversalIdentifiers(- standardAllFlatEntityMaps.flatViewFieldMaps,- ({ viewUniversalIdentifier }) =>- viewUniversalIdentifiers.has(viewUniversalIdentifier),- ),- };-};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.tsdeleted file mode 100644index 0defd68d87a..00000000000--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/find-pending-ask-questions-part.util.ts+++ /dev/null@@ -1,36 +0,0 @@-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.tsindex 9558b3f31e6..a731fc2ed0f 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,7 +83,7 @@ import { ChannelSyncModule } from 'src/modules/connected-account/channel-sync/chimport { 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 { AiToolCallAnswerModule } from 'src/engine/metadata-modules/ai/ai-tool-call-answer/ai-tool-call-answer.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';@@ -129,7 +129,7 @@ import { FileApiModule } from './file/file-api.module';CloudflareModule,DnsManagerModule,WorkflowApiModule,- AnswerAskModule,+ AiToolCallAnswerModule,WorkspaceEventEmitterModule,ActorModule,TelemetryModule,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.tsindex 955e15de95d..c863272d31d 100644--- 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@@ -30,13 +30,6 @@ describe('ASK_QUESTIONS_PAUSING_TOOL', () => {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 () => {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.tsindex d97c173271d..6504c368900 100644--- 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@@ -28,22 +28,18 @@ const toolPart = ({const textPart = { type: 'text', text: 'hello' } as ExtendedUIMessagePart;describe('findAwaitingPausingToolParts', () => {- it('finds the pausing tool call still waiting on an output, with its Ask', () => {+ it('finds the pausing tool call still waiting on an output', () => {expect(findAwaitingPausingToolParts([textPart,toolPart({ toolName: 'ask_questions', status: 'pending' }),]),).toEqual([- {- toolName: 'ask_questions',- toolCallId: 'call-1',- ask: { name: 'q', form: { kind: 'questions', questions: QUESTIONS } },- },+ { toolName: 'ask_questions', toolCallId: 'call-1', isAnswerable: true },]);});- it('finds a waiting call it cannot read, without an Ask', () => {+ it('finds a waiting call it cannot read, as one nobody can answer', () => {expect(findAwaitingPausingToolParts([toolPart({@@ -52,7 +48,9 @@ describe('findAwaitingPausingToolParts', () => {input: { questions: [] },}),]),- ).toEqual([{ toolName: 'ask_questions', toolCallId: 'call-1', ask: null }]);+ ).toEqual([+ { toolName: 'ask_questions', toolCallId: 'call-1', isAnswerable: false },+ ]);});it('finds every waiting call of a step, in the order they were made', () => {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.tsindex 6fd3a03a41c..0e3017942f9 100644--- 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@@ -22,13 +22,6 @@ const buildContext = (toolOutput: Record<string, unknown>) => ({});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' }],[diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/__tests__/request-form.pausing-tool.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/__tests__/request-form.pausing-tool.spec.tsnew file mode 100644index 00000000000..81691625036--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/__tests__/request-form.pausing-tool.spec.ts@@ -0,0 +1,82 @@+import { FieldMetadataType } from 'twenty-shared/types';++import { REQUEST_FORM_PAUSING_TOOL } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/request-form.pausing-tool';+import { requestFormInputSchema } from 'src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool';++const FIELDS = [+ { name: 'company', label: 'Company', type: 'RECORD' as const },+ {+ name: 'closeDate',+ label: 'Close date',+ type: FieldMetadataType.DATE,+ },+];++const parseCall = () => {+ const call = REQUEST_FORM_PAUSING_TOOL.parseCall({ fields: FIELDS });++ if (call === null) {+ throw new Error('Expected the call to parse');+ }++ return call;+};++const NO_TOOLS = { executeTool: jest.fn() };++describe('REQUEST_FORM_PAUSING_TOOL', () => {+ it('reads every field of a workflow form step, however many it has', () => {+ const workflowFormFields = Array.from({ length: 12 }, (_, index) => ({+ ...FIELDS[1],+ id: `field-${index}`,+ name: `date${index}`,+ value: '2026-10-01',+ }));++ expect(+ REQUEST_FORM_PAUSING_TOOL.parseCall({ fields: workflowFormFields }),+ ).not.toBeNull();+ });++ it('holds an agent to a few uniquely named fields', () => {+ const { success: acceptsNoField } = requestFormInputSchema.safeParse({+ fields: [],+ });+ const { success: acceptsSameName } = requestFormInputSchema.safeParse({+ fields: [FIELDS[0], FIELDS[0]],+ });++ expect(acceptsNoField).toBe(false);+ expect(acceptsSameName).toBe(false);+ });++ it('refuses a value for a field the form does not have', () => {+ expect(parseCall().validate({ stage: 'Won' })).toEqual({+ isValid: false,+ errorMessage: 'The form has no field named stage.',+ });+ });++ it('turns the submitted values into the answered result and the answer message', async () => {+ const values = { company: { id: 'company-1' }, closeDate: '2026-10-15' };++ expect(+ await parseCall().complete({ output: values, context: NO_TOOLS }),+ ).toEqual({+ toolResult: {+ success: true,+ message: 'User submitted the form.',+ result: { status: 'answered', values },+ },+ answerText: 'Company: {"id":"company-1"}\nClose date: 2026-10-15',+ });+ });++ it('closes a skipped form without values', () => {+ expect(parseCall().toSkippedToolResult()).toEqual({+ success: true,+ message: 'User skipped the form and sent another message instead.',+ result: { status: 'skipped' },+ });+ });+});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.tsindex 5de761d26b1..a258d75cca5 100644--- 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@@ -102,19 +102,14 @@ const buildAnswerText = ({}).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.+// The chat renderer, the admin panel and the seeded runs all read this result+// shape.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,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.tsindex 8ccf044e961..ba9460c842e 100644--- 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@@ -1,15 +1,18 @@import {ASK_QUESTIONS_TOOL_NAME,PROPOSE_EMAIL_TOOL_NAME,+ REQUEST_FORM_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 { REQUEST_FORM_PAUSING_TOOL } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/request-form.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.+// Tools whose call ends the turn until a person submits its output through+// answerToolCall.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],+ [REQUEST_FORM_TOOL_NAME, REQUEST_FORM_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.tsindex a3398fdf654..29efe7610d5 100644--- 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@@ -57,10 +57,6 @@ export const PROPOSE_EMAIL_PAUSING_TOOL = definePausingTool<>({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.diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/request-form.pausing-tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/request-form.pausing-tool.tsnew file mode 100644index 00000000000..271c3a0e648--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/request-form.pausing-tool.ts@@ -0,0 +1,66 @@+import { isString } from '@sniptt/guards';+import {+ type RequestFormToolInput,+ type RequestFormToolResult,+} from 'twenty-shared/ai';+import { isDefined } 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 { requestFormCallSchema } from 'src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool';++type RequestFormToolOutput = Record<string, unknown>;++const buildRequestFormOutputSchema = ({+ fields,+}: RequestFormToolInput): z.ZodType<RequestFormToolOutput> => {+ const fieldNames = new Set(fields.map((field) => field.name));++ return z.record(z.string(), z.unknown()).superRefine((values, context) => {+ for (const fieldName of Object.keys(values)) {+ if (!fieldNames.has(fieldName)) {+ context.addIssue({+ code: 'custom',+ message: `The form has no field named ${fieldName}.`,+ });+ }+ }+ });+};++const buildAnswerText = ({+ fields,+ values,+}: RequestFormToolInput & { values: RequestFormToolOutput }) =>+ fields+ .filter((field) => isDefined(values[field.name]))+ .map((field) => {+ const value = values[field.name];++ return `${field.label}: ${isString(value) ? value : JSON.stringify(value)}`;+ })+ .join('\n') || 'Submitted the form.';++export const REQUEST_FORM_PAUSING_TOOL = definePausingTool<+ RequestFormToolInput,+ RequestFormToolOutput+>({+ inputSchema: requestFormCallSchema,+ outputSchema: buildRequestFormOutputSchema,+ complete: async ({ output, input: { fields } }) => ({+ toolResult: {+ success: true,+ message: 'User submitted the form.',+ result: {+ status: 'answered',+ values: output,+ } satisfies RequestFormToolResult,+ },+ answerText: buildAnswerText({ fields, values: output }),+ }),+ toSkippedToolResult: () => ({+ success: true,+ message: 'User skipped the form and sent another message instead.',+ result: { status: 'skipped' } satisfies RequestFormToolResult,+ }),+});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.tsdeleted file mode 100644index cdd584c2f64..00000000000--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-ask.type.ts+++ /dev/null@@ -1,6 +0,0 @@-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.tsindex f4de3989e0f..91630da50da 100644--- 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@@ -1,4 +1,3 @@-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';@@ -7,7 +6,6 @@ export type PausingToolValidation =| { isValid: false; errorMessage: string };export type PausingToolCall = {- buildAsk: () => PausingToolAsk;validate: (output: unknown) => PausingToolValidation;// Takes an output validate accepted.complete: (args: {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.tsindex ef976a729f6..15606617a7f 100644--- 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@@ -1,6 +1,5 @@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';@@ -9,7 +8,6 @@ export type PausingToolDefinition<TInput, TOutput> = {// 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.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.tsindex 4bd39a9e6fd..a1aee7d3bb2 100644--- 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@@ -24,7 +24,6 @@ export const definePausingTool = <const outputSchema = definition.outputSchema(input);return {- buildAsk: () => definition.buildAsk(input),toSkippedToolResult: () => definition.toSkippedToolResult(input),validate: (output) => {const parsedOutput = outputSchema.safeParse(output);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.tsindex 58cd29adba2..ad60c18179f 100644--- 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@@ -3,17 +3,16 @@ 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.+// A call whose input cannot be read cannot be answered.export type AwaitingPausingToolPart = {toolName: string;toolCallId: string;- ask: PausingToolAsk | null;+ isAnswerable: boolean;};-// A step can call several pausing tools at once: each waits on its own Ask,-// in the order the model made the calls.+// A step can call several pausing tools at once, and each waits on its own+// answer.export const findAwaitingPausingToolParts = (parts: ExtendedUIMessagePart[],): AwaitingPausingToolPart[] =>@@ -33,7 +32,7 @@ export const findAwaitingPausingToolParts = ({toolName,toolCallId: part.toolCallId,- ask: pausingTool.parseCall(part.input)?.buildAsk() ?? null,+ isAnswerable: isDefined(pausingTool.parseCall(part.input)),},];});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/skip-awaiting-tool-parts.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/skip-awaiting-tool-parts.util.tsnew file mode 100644index 00000000000..72377a89e30--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/skip-awaiting-tool-parts.util.ts@@ -0,0 +1,39 @@+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 AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';+import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';++// Closes the calls a message still waits on once nothing will answer them, so+// the model and the conversation both show they went unanswered.+export const skipAwaitingToolParts = async ({+ messagePartRepository,+ messageId,+ workspaceId,+}: {+ messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>;+ messageId: string;+ workspaceId: string;+}): Promise<void> => {+ const parts = await messagePartRepository.find(workspaceId, {+ where: { messageId },+ select: ['id', 'toolName', 'toolInput', 'toolOutput'],+ });++ for (const part of parts) {+ const pausingTool = isDefined(part.toolName)+ ? PAUSING_TOOLS.get(part.toolName)+ : undefined;+ const pausingToolCall = pausingTool?.isAwaitingOutput(part.toolOutput)+ ? pausingTool.parseCall(part.toolInput)+ : null;++ if (isDefined(pausingToolCall)) {+ await messagePartRepository.update(+ workspaceId,+ { id: part.id },+ { toolOutput: pausingToolCall.toSkippedToolResult() },+ );+ }+ }+};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.tsindex 48d1c7f2762..4b2559307c3 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@@ -49,8 +49,6 @@ import { ChatExecutionService } from './services/chat-execution.service';import { MessagePruningService } from './services/message-pruning.service';import { SystemPromptBuilderService } from './services/system-prompt-builder.service';-import { InputAskModule } from 'src/modules/input-ask/input-ask.module';-@Module({imports: [RecordShareModule,@@ -81,7 +79,6 @@ import { InputAskModule } from 'src/modules/input-ask/input-ask.module';ToolProviderModule,DashboardToolsModule,WorkflowToolsModule,- InputAskModule,],providers: [AgentChatActorService,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.tsindex 98f516c8ad0..d74fe33a32e 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@@ -204,9 +204,7 @@ describe('StreamAgentChatJob', () => {inputCostPerMillionTokens: 1,outputCostPerMillionTokens: 2,},- inputAskOpenRejection,}: {- inputAskOpenRejection?: Error;workspaceFound?: boolean;chatStream?: ReturnType<typeof createFakeChatStream>;streamChatRejection?: Error;@@ -306,12 +304,6 @@ 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,@@ -324,7 +316,6 @@ describe('StreamAgentChatJob', () => {metricsService as never,aiModelRegistryService as never,actorService as never,- inputAskWorkspaceService as never,);const turnCounts = (key: string) =>@@ -345,7 +336,6 @@ describe('StreamAgentChatJob', () => {cancelCallbacks,metricsService,aiModelRegistryService,- inputAskWorkspaceService,turnCounts,};};@@ -860,105 +850,54 @@ 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 }),- });+ const pendingQuestionMessageIdOf = (threadUsageQuery: jest.Mock) =>+ (threadUsageQuery.mock.calls[0] as unknown as [string, unknown[]])[1][10];++ it('marks the conversation as waiting on the message that paused, in the totals write, and leaves the queue waiting', async () => {+ const { job, threadUsageQuery, 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(pendingQuestionMessageIdOf(threadUsageQuery)).toEqual(+ expect.any(String),+ );expect(agentChatStreamingService.flushNextQueuedMessage,).not.toHaveBeenCalled();});- it('opens no Ask for a turn that did not pause', async () => {- const { job, inputAskWorkspaceService } = buildJob();+ it('leaves a conversation whose turn did not pause waiting on nothing', async () => {+ const { job, threadUsageQuery } = buildJob();await job.handle(jobData);- expect(inputAskWorkspaceService.open).not.toHaveBeenCalled();+ expect(pendingQuestionMessageIdOf(threadUsageQuery)).toBeNull();});- 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'),+ it('fails the turn, leaving it retryable, when a paused call cannot be read', async () => {+ const { job, threadUsageQuery, publishedEvents, turnCounts } = buildJob({+ chatStream: createFakeChatStream({+ parts: PENDING_QUESTION_PARTS.map((part) =>+ part.type === 'tool-call' || part.type === 'tool-result'+ ? { ...part, input: { questions: [] } }+ : part,+ ),+ }),});- 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',- }),- },+ await expect(job.handle(jobData)).rejects.toThrow(+ 'A call waiting on the user could not be read',);++ expect(pendingQuestionMessageIdOf(threadUsageQuery)).toBeNull();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 a reply as answered when the model recovers from a failed tool call', async () => {const { job, publishedEvents, 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.tsindex 5cd1aa721f8..97da0773a74 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,10 +36,7 @@ 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 { 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';@@ -61,7 +58,6 @@ import type { AiModelConfig } from 'src/engine/metadata-modules/ai/ai-models/typimport { 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 };@@ -79,8 +75,8 @@ 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.+ // Set once the turn has paused on a person, which is what the queue waits+ // on: a queued message drained now would bypass the answer it is waiting for.private isAwaitingInput = false;constructor(@@ -97,7 +93,6 @@ 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)@@ -828,6 +823,11 @@ export class StreamAgentChatJob {);const awaitingParts = findAwaitingPausingToolParts(responseMessage.parts);+ // Without an answerable call nothing can resume the turn, so it fails and+ // can be retried rather than wait forever.+ const isAwaitingAnswer =+ awaitingParts.length > 0 &&+ awaitingParts.every(({ isAnswerable }) => isAnswerable);if ((isAborted || !hasText) && awaitingParts.length === 0) {this.logAssistantTurnWithoutText({@@ -888,6 +888,7 @@ export class StreamAgentChatJob {totalCacheCreationTokens,contextWindowTokens: modelConfig.contextWindowTokens,conversationSize: lastStepConversationSize,+ pendingQuestionMessageId: isAwaitingAnswer ? assistantMessageId : null,},});@@ -895,12 +896,14 @@ export class StreamAgentChatJob {return resolveSupersededTurnOutcome(outcome);}- await this.openAsksForAwaitingParts({- awaitingParts,- threadId,- workspaceId,- workspaceMemberId,- });+ if (awaitingParts.length > 0 && !isAwaitingAnswer) {+ throw new AiException(+ 'A call waiting on the user could not be read',+ AiExceptionCode.INVALID_TOOL_CALL_OUTPUT,+ );+ }++ this.isAwaitingInput = isAwaitingAnswer;await this.agentChatService.notifyThreadUsageUpdated({threadBefore: threadBeforeUsage,@@ -911,56 +914,6 @@ 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/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.tsindex 5ec3df4a6ca..bec28a056d8 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,5 +1,3 @@-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';@@ -29,11 +27,14 @@ describe('AgentChatStreamingService claim & reap', () => {claimAffected = 1,queuedMessages = [] as unknown[],heartbeatAlive = true,- pendingInputAsk = null as {- id: string;- toolCallId: string;- workflowRunId: string | null;- } | null,+ }: {+ thread?: typeof idleThread & {+ pendingQuestionMessageId?: string;+ workflowRunId?: string;+ };+ claimAffected?: number;+ queuedMessages?: unknown[];+ heartbeatAlive?: boolean;} = {}) => {const publishedEvents: Array<{ type: string }> = [];const threadRepository = {@@ -58,24 +59,17 @@ 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 messagePartRepository = {+ find: jest.fn().mockResolvedValue([+ {+ id: 'part-id',+ toolName: 'ask_questions',+ toolInput: { questions: QUESTIONS },+ toolOutput: { result: { questions: QUESTIONS, status: 'pending' } },+ },+ ]),+ update: jest.fn().mockResolvedValue({ affected: 1 }),};const eventPublisherService = {publish: jest.fn().mockImplementation(({ event }) => {@@ -121,12 +115,12 @@ describe('AgentChatStreamingService claim & reap', () => {},}),} as never,- inputAskWorkspaceService as never,+ messagePartRepository as never,);return {service,- inputAskWorkspaceService,+ messagePartRepository,threadRepository,messageQueueService,agentChatService,@@ -241,68 +235,65 @@ describe('AgentChatStreamingService claim & reap', () => {);});- it('cancels a pending chat Ask and closes its call as skipped before streaming', async () => {+ const waitingThread = {+ ...idleThread,+ pendingQuestionMessageId: 'question-message-id',+ };++ it('stops waiting and closes the pending call as skipped before streaming', async () => {const {service,- inputAskWorkspaceService,- agentChatService,+ threadRepository,+ messagePartRepository,messageQueueService,- } = buildService({- pendingInputAsk: {- id: 'input-ask-id',- toolCallId: 'tool-call-id',- workflowRunId: null,- },- });+ } = buildService({ thread: waitingThread });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(threadRepository.update).toHaveBeenCalledWith(+ 'workspace-id',+ {+ id: 'thread-id',+ pendingQuestionMessageId: 'question-message-id',+ activeStreamId: expect.anything(),+ },+ { pendingQuestionMessageId: null },+ );+ expect(messagePartRepository.update).toHaveBeenCalledWith(+ 'workspace-id',+ { id: 'part-id' },+ {+ toolOutput: expect.objectContaining({+ result: { questions: QUESTIONS, status: 'skipped' },+ }),+ },+ );expect(- agentChatService.updateToolPartOutput.mock.invocationCallOrder[0],+ messagePartRepository.update.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,- },- });+ it('leaves the call as it is when an answer holds the conversation', async () => {+ const { service, threadRepository, messagePartRepository } = buildService(+ { thread: waitingThread },+ );- inputAskWorkspaceService.cancel.mockResolvedValue(false);+ threadRepository.update.mockResolvedValueOnce({ affected: 0 });await service.streamAgentChat(sendArguments);- expect(agentChatService.updateToolPartOutput).not.toHaveBeenCalled();+ expect(messagePartRepository.update).not.toHaveBeenCalled();});- it("refuses a message while the run's Ask is pending, without canceling it", async () => {+ it('refuses a message while its workflow run waits on the conversation', async () => {const {service,- inputAskWorkspaceService,+ messagePartRepository,agentChatService,messageQueueService,} = buildService({- pendingInputAsk: {- id: 'input-ask-id',- toolCallId: 'tool-call-id',- workflowRunId: 'workflow-run-id',- },+ thread: { ...waitingThread, workflowRunId: 'workflow-run-id' },});await expect(@@ -310,7 +301,7 @@ describe('AgentChatStreamingService claim & reap', () => {).rejects.toMatchObject({code: AiExceptionCode.THREAD_AWAITING_WORKFLOW_INPUT,});- expect(inputAskWorkspaceService.cancel).not.toHaveBeenCalled();+ expect(messagePartRepository.update).not.toHaveBeenCalled();expect(agentChatService.addMessage).not.toHaveBeenCalled();expect(agentChatService.queueMessage).not.toHaveBeenCalled();expect(messageQueueService.add).not.toHaveBeenCalled();@@ -347,13 +338,12 @@ describe('AgentChatStreamingService claim & reap', () => {},];- it('keeps queued messages waiting behind a pending Ask', async () => {+ it('keeps queued messages waiting behind a pending call', async () => {const { service, agentChatService, messageQueueService } = buildService({queuedMessages,- pendingInputAsk: {- id: 'input-ask-id',- toolCallId: 'tool-call-id',- workflowRunId: null,+ thread: {+ ...idleThread,+ pendingQuestionMessageId: 'question-message-id',},});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.tsindex f4bd1b50425..55fe1ec57c5 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@@ -29,10 +29,11 @@ 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 { skipAwaitingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/skip-awaiting-tool-parts.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';+import { AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';import { type AgentChatThreadLastStreamError } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-last-stream-error.type';import { STREAM_AGENT_CHAT_JOB_NAME } from 'src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat-job-name.constant';import { type StreamAgentChatJobData } from 'src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat-job.types';@@ -47,7 +48,6 @@ 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;@@ -79,7 +79,8 @@ export class AgentChatStreamingService {private readonly metricsService: MetricsService,private readonly streamRecoveryService: AgentChatStreamRecoveryService,private readonly actorService: AgentChatActorService,- private readonly inputAskWorkspaceService: InputAskWorkspaceService,+ @InjectAgentHistoryRepository('agentMessagePart')+ private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>,) {}async reapDeadStream({@@ -149,8 +150,8 @@ export class AgentChatStreamingService {});const [, hasQueuedBacklog] = await Promise.all([- this.settlePendingInputAsksBeforeSending({- threadId,+ this.settlePendingToolCallsBeforeSending({+ thread,workspaceId: workspace.id,}),this.agentChatService.hasQueuedMessages({@@ -592,20 +593,15 @@ export class AgentChatStreamingService {}): Promise<void> {const threadStatus = await this.threadRepository.findOne(workspaceId, {where: { id: threadId },- select: ['id', 'deletedAt'],+ select: ['id', 'deletedAt', 'pendingQuestionMessageId'],});- if (!threadStatus || threadStatus.deletedAt) {- return;- }-- // Queued messages wait behind an Ask: they are the conversation after- // the answer, not a replacement for it.+ // Queued messages wait behind a pending tool call: they are the+ // conversation after the answer, not a replacement for it.if (- await this.inputAskWorkspaceService.hasPendingForThread({- threadId,- workspaceId,- })+ !threadStatus ||+ threadStatus.deletedAt ||+ isDefined(threadStatus.pendingQuestionMessageId)) {return;}@@ -771,72 +767,50 @@ export class AgentChatStreamingService {}// 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,+ // past its pending calls, which are closed as skipped so the model sees why+ // they went unanswered. Clearing the marker is the claim, and an answer+ // holding the stream keeps it. A workflow run's calls gate the run, so a+ // chat message never closes them.+ private async settlePendingToolCallsBeforeSending({+ thread,workspaceId,}: {- threadId: string;+ thread: Pick<+ AgentChatThreadWorkspaceEntity,+ 'id' | 'workflowRunId' | 'pendingQuestionMessageId'+ >;workspaceId: string;}): Promise<void> {- const pendingInputAsks =- await this.inputAskWorkspaceService.findPendingForThread({- threadId,- workspaceId,- });+ const messageId = thread.pendingQuestionMessageId;- if (- pendingInputAsks.some((pendingInputAsk) =>- isDefined(pendingInputAsk.workflowRunId),- )- ) {+ if (!isDefined(messageId)) {+ return;+ }++ if (isDefined(thread.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,+ const claim = await this.threadRepository.update(workspaceId,- });- const pausingToolCall = parsePausingToolCall(toolPart);+ {+ id: thread.id,+ pendingQuestionMessageId: messageId,+ activeStreamId: IsNull(),+ },+ { pendingQuestionMessageId: null },+ );- if (!isDefined(toolPart) || !isDefined(pausingToolCall)) {+ if (!claim.affected) {return;}- await this.agentChatService.updateToolPartOutput({- partId: toolPart.id,- toolOutput: pausingToolCall.toSkippedToolResult(),+ await skipAwaitingToolParts({+ messagePartRepository: this.messagePartRepository,+ messageId,workspaceId,});}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.tsindex d8b9fc8a485..534d5b32687 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@@ -21,6 +21,8 @@ import {import { AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';import { AgentTurnWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-turn.workspace-entity';import { mapUIMessagePartsToPersistedDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-persisted-db-parts.util';+import { PAUSING_TOOLS } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant';+import { skipAwaitingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/skip-awaiting-tool-parts.util';import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';import {AiException,@@ -590,13 +592,13 @@ export class AgentChatService {}): Promise<| (Pick<AgentMessagePartWorkspaceEntity,- 'id' | 'messageId' | 'toolName' | 'toolInput'+ 'id' | 'messageId' | 'toolName' | 'toolInput' | 'toolOutput'> & { turnId: string | null })| null> {const parts = await this.messagePartRepository.find(workspaceId, {where: { toolCallId },- select: ['id', 'messageId', 'toolName', 'toolInput'],+ select: ['id', 'messageId', 'toolName', 'toolInput', 'toolOutput'],});if (!isNonEmptyArray(parts)) {@@ -618,20 +620,89 @@ export class AgentChatService {: null;}- async updateToolPartOutput({+ async findAwaitingToolParts({+ messageId,+ workspaceId,+ }: {+ messageId: string;+ workspaceId: string;+ }): Promise<+ Pick<+ AgentMessagePartWorkspaceEntity,+ 'id' | 'toolName' | 'toolCallId' | 'toolInput'+ >[]+ > {+ const parts = await this.messagePartRepository.find(workspaceId, {+ where: { messageId },+ select: ['id', 'toolName', 'toolCallId', 'toolInput', 'toolOutput'],+ });++ return parts.filter(+ (part) =>+ isDefined(part.toolName) &&+ (PAUSING_TOOLS.get(part.toolName)?.isAwaitingOutput(part.toolOutput) ??+ false),+ );+ }++ // The answer and, once no call of the message still waits, the+ // conversation no longer waiting on it are written together, so an answer+ // never strands a conversation waiting on calls that are all answered.+ async recordToolCallAnswer({+ threadId,+ messageId,partId,toolOutput,+ isLastAnswer,workspaceId,}: {+ threadId: string;+ messageId: string;partId: string;toolOutput: Record<string, unknown>;+ isLastAnswer: boolean;+ workspaceId: string;+ }): Promise<void> {+ await this.messagePartRepository.query(+ workspaceId,+ async ({ manager, table }) => {+ await manager.query(+ `UPDATE ${table('agentMessagePart')} SET "toolOutput" = $2::jsonb, "updatedAt" = now() WHERE id = $1`,+ [partId, JSON.stringify(toolOutput)],+ );++ if (isLastAnswer) {+ await manager.query(+ `UPDATE ${table('agentChatThread')} SET "pendingQuestionMessageId" = NULL, "updatedAt" = now() WHERE id = $1 AND "pendingQuestionMessageId" = $2`,+ [threadId, messageId],+ );+ }+ },+ );+ }++ // Calls nothing can answer anymore are closed, so the conversation no longer+ // waits on them.+ async closePendingToolCalls({+ threadId,+ messageId,+ workspaceId,+ }: {+ threadId: string;+ messageId: string;workspaceId: string;}): Promise<void> {- await this.messagePartRepository.update(+ await this.threadRepository.update(workspaceId,- { id: partId },- { toolOutput },+ { id: threadId, pendingQuestionMessageId: messageId },+ { pendingQuestionMessageId: null },);++ await skipAwaitingToolParts({+ messagePartRepository: this.messagePartRepository,+ messageId,+ workspaceId,+ });}// Sending to a soft deleted conversation brings it back to the listdiff --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.tsindex 9379eabd11e..7f5c556c099 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@@ -78,6 +78,10 @@ import {PROPOSE_EMAIL_TOOL_NAME,createProposeEmailTool,} from 'src/engine/metadata-modules/ai/ai-chat/tools/propose-email.tool';+import {+ REQUEST_FORM_TOOL_NAME,+ createRequestFormTool,+} from 'src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool';import {COMPLETE_WORKSPACE_SETUP_TOOL_NAME,createCompleteWorkspaceSetupTool,@@ -315,6 +319,7 @@ export class ChatExecutionService {...Object.keys(preloadedTools),...Object.keys(nativeTools),ASK_QUESTIONS_TOOL_NAME,+ REQUEST_FORM_TOOL_NAME,...(canProposeEmail ? [PROPOSE_EMAIL_TOOL_NAME] : []),...(isWorkspaceSetupThread ? [COMPLETE_WORKSPACE_SETUP_TOOL_NAME] : []),...(canAttachConversationToRecords@@ -332,6 +337,7 @@ export class ChatExecutionService {[ASK_QUESTIONS_TOOL_NAME]: createAskQuestionsTool({isWorkspaceSetupThread,}),+ [REQUEST_FORM_TOOL_NAME]: createRequestFormTool(),...(canProposeEmail? { [PROPOSE_EMAIL_TOOL_NAME]: createProposeEmailTool() }: {}),diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool.tsnew file mode 100644index 00000000000..3f3566e56c4--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool.ts@@ -0,0 +1,65 @@+import {+ REQUEST_FORM_TOOL_NAME,+ type RequestFormToolInput,+ type RequestFormToolResult,+} from 'twenty-shared/ai';+import { workflowFormFieldSchema } from 'twenty-shared/workflow';+import { z } from 'zod';++export { REQUEST_FORM_TOOL_NAME };++const requestFormFieldSchema = workflowFormFieldSchema.pick({+ name: true,+ label: true,+ type: true,+ placeholder: true,+ settings: true,+});++// A form step issues this call with every field of its form, so a recorded+// call is read without the limits an agent is held to.+export const requestFormCallSchema = z.object({+ fields: z.array(requestFormFieldSchema),+});++export const requestFormInputSchema = z.object({+ fields: z+ .array(requestFormFieldSchema)+ .min(1)+ .max(10)+ .refine(+ (fields) =>+ new Set(fields.map((field) => field.name)).size === fields.length,+ { message: 'Each field needs its own name.' },+ )+ .describe(+ 'The fields to fill in, in order. Each name is unique and keys its value in the result. ' ++ 'A RECORD field needs settings.objectName, the singular name of the object to pick from (e.g. "company"). ' ++ 'A SELECT or MULTI_SELECT field needs settings.selectedFieldId, the id of an existing select field whose options it offers.',+ ),+});++type RequestFormPendingOutput = {+ success: true;+ message: string;+ result: RequestFormToolResult;+};++// A workflow form step writes the same output when it issues this call.+export const buildRequestFormPendingOutput = (): RequestFormPendingOutput => ({+ success: true,+ message: 'Form presented to the user; awaiting their answer.',+ result: { status: 'pending' },+});++export const createRequestFormTool = () => ({+ description:+ 'Ask the user to fill in a form when you need typed values from them: text, numbers, dates, ' ++ 'options of an existing select field, or records picked from the workspace. The conversation ' ++ 'pauses until they submit it, then continues with the values keyed by field name. Prefer ' ++ 'ask_questions for a choice between a few options you can list yourself.',+ inputSchema: requestFormInputSchema,+ execute: async (+ _input: RequestFormToolInput,+ ): Promise<RequestFormPendingOutput> => buildRequestFormPendingOutput(),+});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.tsindex b28f6bad1de..147cf7b1cd4 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,6 +10,7 @@ type ThreadUsageUpdate = {totalCacheCreationTokens: number;contextWindowTokens: number | null;conversationSize: number;+ pendingQuestionMessageId: string | null;};export const updateAgentChatThreadUsage = async ({@@ -39,7 +40,7 @@ export const updateAgentChatThreadUsage = async ({"totalCacheReadTokens" = "totalCacheReadTokens" + $7,"totalCacheCreationTokens" = "totalCacheCreationTokens" + $8,"contextWindowTokens" = $9, "conversationSize" = $10,- "lastStreamError" = NULL, "updatedAt" = now()+ "pendingQuestionMessageId" = $11, "lastStreamError" = NULL, "updatedAt" = now()WHERE id = $1 AND "activeStreamId" = $2RETURNING id) SELECT id FROM updated`,@@ -54,6 +55,7 @@ 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-history/standard-objects/agent-chat-thread.workspace-entity.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity.tsindex afac947e98c..116c649756c 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity.ts@@ -1,4 +1,3 @@-import { type InputAskWorkspaceEntity } from 'src/modules/input-ask/standard-objects/input-ask.workspace-entity';import { type AttachmentWorkspaceEntity } from 'src/modules/attachment/standard-objects/attachment.workspace-entity';import { type EntityRelation } from 'src/engine/workspace-manager/workspace-migration/types/entity-relation.interface';import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';@@ -16,7 +15,6 @@ export class AgentChatThreadWorkspaceEntity extends BaseWorkspaceEntity {workspaceMember: EntityRelation<WorkspaceMemberWorkspaceEntity> | null;recordTargets: EntityRelation<AgentChatThreadTargetWorkspaceEntity[]>;workflowRun: EntityRelation<WorkflowRunWorkspaceEntity> | null;- inputAsks: EntityRelation<InputAskWorkspaceEntity[]>;archivedAt: string | null;userWorkspaceId: string | null;diff --git a/packages/twenty-server/src/modules/input-ask/answer-ask/answer-ask.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/ai-tool-call-answer.module.tssimilarity index 66%rename from packages/twenty-server/src/modules/input-ask/answer-ask/answer-ask.module.tsrename to packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/ai-tool-call-answer.module.tsindex e7b550500d8..dae45a810f7 100644--- a/packages/twenty-server/src/modules/input-ask/answer-ask/answer-ask.module.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/ai-tool-call-answer.module.ts@@ -5,23 +5,25 @@ import { AiAgentExecutionModule } from 'src/engine/metadata-modules/ai/ai-agent-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 { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';+import { AnswerAgentChatQuestionResolver } from 'src/engine/metadata-modules/ai/ai-tool-call-answer/resolvers/answer-agent-chat-question.resolver';+import { ToolCallAnswerResolver } from 'src/engine/metadata-modules/ai/ai-tool-call-answer/resolvers/tool-call-answer.resolver';+import { ToolCallAnswerService } from 'src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service';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';+// Answering a paused call can resume a chat or a workflow run, so this sits+// above both.@Module({imports: [+ AgentHistoryModule,AiAgentExecutionModule,AiChatModule,AgentChatStreamStateModule,AiBillingModule,- InputAskModule,PermissionsModule,ToolProviderModule,WorkflowRunModule,@@ -29,10 +31,10 @@ import { WorkflowRunnerModule } from 'src/modules/workflow/workflow-runner/workfWorkspaceCacheModule,],providers: [- AnswerAskService,- AnswerAskResolver,+ ToolCallAnswerService,+ ToolCallAnswerResolver,AnswerAgentChatQuestionResolver,AiGraphqlApiExceptionInterceptor,],})-export class AnswerAskModule {}+export class AiToolCallAnswerModule {}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/dtos/answer-tool-call-result.dto.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/dtos/answer-tool-call-result.dto.tsnew file mode 100644index 00000000000..031a80503c8--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/dtos/answer-tool-call-result.dto.ts@@ -0,0 +1,9 @@+import { Field, ObjectType } from '@nestjs/graphql';++@ObjectType('AnswerToolCallResult')+export class AnswerToolCallResultDTO {+ // Only a chat conversation resumes as a stream, once its last call is+ // answered; 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/engine/metadata-modules/ai/ai-tool-call-answer/dtos/answer-tool-call.input.tssimilarity index 59%rename from packages/twenty-server/src/modules/input-ask/answer-ask/dtos/answer-ask.input.tsrename to packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/dtos/answer-tool-call.input.tsindex e21e20f20ea..9d02da4b209 100644--- a/packages/twenty-server/src/modules/input-ask/answer-ask/dtos/answer-ask.input.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/dtos/answer-tool-call.input.ts@@ -1,19 +1,29 @@import { Field, InputType } from '@nestjs/graphql';-import { IsObject, IsOptional, IsString, IsUUID } from 'class-validator';+import {+ IsNotEmpty,+ 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 {+export class AnswerToolCallInput {@Field(() => UUIDScalarType)@IsUUID()- askId: string;+ threadId: string;++ @Field(() => String)+ @IsString()+ @IsNotEmpty()+ toolCallId: string;@Field(() => GraphQLJSON, {- description:- 'The answer, validated against what the Ask asked (its form kind)',+ description: 'The answer, validated against what the tool call asked',})@IsObject()response: Record<string, unknown>;diff --git a/packages/twenty-server/src/modules/input-ask/answer-ask/resolvers/answer-agent-chat-question.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/resolvers/answer-agent-chat-question.resolver.tssimilarity index 84%rename from packages/twenty-server/src/modules/input-ask/answer-ask/resolvers/answer-agent-chat-question.resolver.tsrename to packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/resolvers/answer-agent-chat-question.resolver.tsindex b972c9117ca..a3c20425f61 100644--- a/packages/twenty-server/src/modules/input-ask/answer-ask/resolvers/answer-agent-chat-question.resolver.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/resolvers/answer-agent-chat-question.resolver.ts@@ -27,17 +27,16 @@ import { FileAttachmentInput } from 'src/engine/metadata-modules/ai/ai-chat/dtosimport { 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 { ToolCallAnswerService } from 'src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service';import {- InputAskException,- InputAskExceptionCode,-} from 'src/modules/input-ask/input-ask.exception';+ AiException,+ AiExceptionCode,+} from 'src/engine/metadata-modules/ai/ai.exception';+import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';-// 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.+// The metadata API's answer mutation from before answerToolCall, kept so+// clients built against it keep working for a release. It answers the+// questions the message asked, with the same checks as answerToolCall.@MetadataResolver()@UsePipes(ResolverValidationPipe)@UseGuards(@@ -55,7 +54,6 @@ import {)@UseInterceptors(AiGraphqlApiExceptionInterceptor)@UseFilters(- InputAskGraphqlApiExceptionFilter,UsageLimitGraphqlApiExceptionFilter,BillingGraphqlApiExceptionFilter,PermissionsGraphqlApiExceptionFilter,@@ -64,10 +62,10 @@ import {AuthGraphqlApiExceptionFilter,)export class AnswerAgentChatQuestionResolver {- constructor(private readonly answerAskService: AnswerAskService) {}+ constructor(private readonly toolCallAnswerService: ToolCallAnswerService) {}@Mutation(() => SendChatMessageResultDTO, {- deprecationReason: "Use answerAsk with the question's Ask",+ deprecationReason: 'Use answerToolCall with the questions tool call',})@UseGuards(CustomPermissionGuard)async answerAgentChatQuestion(@@ -87,14 +85,14 @@ export class AnswerAgentChatQuestionResolver {@AuthWorkspace() workspace: WorkspaceEntity,): Promise<SendChatMessageResultDTO> {if (isNonEmptyArray(fileAttachments)) {- throw new InputAskException(+ throw new AiException('Files can no longer be sent with an answer: send them in a message',- InputAskExceptionCode.INVALID_ASK_RESPONSE,+ AiExceptionCode.INVALID_TOOL_CALL_OUTPUT,);}const { streamId, turnId } =- await this.answerAskService.answerQuestionsOfMessage({+ await this.toolCallAnswerService.answerQuestionsOfMessage({threadId,messageId,response: { answers: answers.map((answer) => ({ ...answer })) },diff --git a/packages/twenty-server/src/modules/input-ask/answer-ask/resolvers/answer-ask.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/resolvers/tool-call-answer.resolver.tssimilarity index 74%rename from packages/twenty-server/src/modules/input-ask/answer-ask/resolvers/answer-ask.resolver.tsrename to packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/resolvers/tool-call-answer.resolver.tsindex 972e07a3c4b..c029339ab2b 100644--- a/packages/twenty-server/src/modules/input-ask/answer-ask/resolvers/answer-ask.resolver.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/resolvers/tool-call-answer.resolver.ts@@ -24,19 +24,18 @@ import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';import { CustomPermissionGuard } from 'src/engine/guards/custom-permission.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 { AnswerToolCallResultDTO } from 'src/engine/metadata-modules/ai/ai-tool-call-answer/dtos/answer-tool-call-result.dto';+import { AnswerToolCallInput } from 'src/engine/metadata-modules/ai/ai-tool-call-answer/dtos/answer-tool-call.input';+import { ToolCallAnswerService } from 'src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service';import {- InputAskException,- InputAskExceptionCode,-} from 'src/modules/input-ask/input-ask.exception';+ AiException,+ AiExceptionCode,+} from 'src/engine/metadata-modules/ai/ai.exception';+import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';-// 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.+// Served on /graphql: the permission an answer needs depends on whether the+// call waits in a chat or in a workflow run, so it is checked per call rather+// than by a class guard.@CoreResolver()@UsePipes(ResolverValidationPipe)@UseGuards(@@ -54,7 +53,6 @@ import {)@UseInterceptors(AiGraphqlApiExceptionInterceptor)@UseFilters(- InputAskGraphqlApiExceptionFilter,UsageLimitGraphqlApiExceptionFilter,BillingGraphqlApiExceptionFilter,PermissionsGraphqlApiExceptionFilter,@@ -62,19 +60,21 @@ import {PreventNestToAutoLogGraphqlErrorsFilter,AuthGraphqlApiExceptionFilter,)-export class AnswerAskResolver {- constructor(private readonly answerAskService: AnswerAskService) {}+export class ToolCallAnswerResolver {+ constructor(private readonly toolCallAnswerService: ToolCallAnswerService) {}- @Mutation(() => AnswerAskResultDTO)+ @Mutation(() => AnswerToolCallResultDTO)@UseGuards(CustomPermissionGuard)- async answerAsk(- @Args('input') { askId, response, modelId }: AnswerAskInput,+ async answerToolCall(+ @Args('input')+ { threadId, toolCallId, response, modelId }: AnswerToolCallInput,@AuthUserWorkspaceId() userWorkspaceId: string,@AuthWorkspaceMemberId() workspaceMemberId: string,@AuthWorkspace() workspace: WorkspaceEntity,- ): Promise<AnswerAskResultDTO> {- const { streamId, threadId, turnId } = await this.answerAskService.answer({- askId,+ ): Promise<AnswerToolCallResultDTO> {+ const { streamId, turnId } = await this.toolCallAnswerService.answer({+ threadId,+ toolCallId,response,modelId,userWorkspaceId,@@ -82,7 +82,7 @@ export class AnswerAskResolver {workspace,});- if (isDefined(streamId) && isDefined(threadId)) {+ if (isDefined(streamId)) {tagAiChatStreamScope({streamId,turnId,@@ -94,9 +94,10 @@ export class AnswerAskResolver {return { streamId };}- // Kept so clients built before answerAsk keep working for a release.+ // Kept so clients built before answerToolCall keep working for a release.@Mutation(() => Boolean, {- deprecationReason: "Use answerAsk with the form step's Ask",+ deprecationReason:+ "Use answerToolCall with the step's thread and the step id as toolCallId",})@UseGuards(CustomPermissionGuard)async submitFormStep(@@ -106,13 +107,13 @@ export class AnswerAskResolver {@AuthWorkspace() workspace: WorkspaceEntity,): Promise<boolean> {if (!isPlainObject(response)) {- throw new InputAskException(+ throw new AiException('A form response must be an object',- InputAskExceptionCode.INVALID_ASK_RESPONSE,+ AiExceptionCode.INVALID_TOOL_CALL_OUTPUT,);}- await this.answerAskService.answerFormStepByStep({+ await this.toolCallAnswerService.answerFormStep({workflowRunId,stepId,response,diff --git a/packages/twenty-server/src/modules/input-ask/answer-ask/services/__tests__/answer-ask.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/__tests__/tool-call-answer.service.spec.tssimilarity index 59%rename from packages/twenty-server/src/modules/input-ask/answer-ask/services/__tests__/answer-ask.service.spec.tsrename to packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/__tests__/tool-call-answer.service.spec.tsindex c1e9428eb73..4aaf55b2801 100644--- a/packages/twenty-server/src/modules/input-ask/answer-ask/services/__tests__/answer-ask.service.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/__tests__/tool-call-answer.service.spec.ts@@ -1,8 +1,7 @@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';+import { ToolCallAnswerService } from 'src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service';const QUESTIONS = [{@@ -20,25 +19,9 @@ const PROPOSED_EMAIL = {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 FORM_FIELDS = [+ { id: 'field-id', name: 'discount', label: 'Discount', type: 'TEXT' },+];const questionPart = {id: 'part-id',@@ -49,11 +32,28 @@ const questionPart = {toolOutput: { result: { questions: QUESTIONS, status: 'pending' } },};-describe('AnswerAskService', () => {+const waitingThread = {+ id: 'thread-id',+ workflowRunId: null as string | null,+ activeStreamId: null,+ pendingQuestionMessageId: 'question-message-id',+};++type BuildOptions = {+ thread?: typeof waitingThread | null;+ toolPart?: Record<string, unknown> | null;+ hasClaimedStream?: boolean;+ isStillAwaiting?: boolean;+ hasOtherAwaitingCalls?: boolean;+ hasPermission?: boolean;+};++describe('ToolCallAnswerService', () => {const workspace = { id: 'workspace-id' } as WorkspaceEntity;const answerArguments = {- askId: 'ask-id',+ threadId: 'thread-id',+ toolCallId: 'tool-call-id',response: { answers: ANSWERS } as Record<string, unknown>,userWorkspaceId: 'user-workspace-id',workspaceMemberId: 'member-id',@@ -61,24 +61,31 @@ describe('AnswerAskService', () => {};const buildService = ({- inputAsk = chatInputAsk,+ thread = waitingThread,toolPart = questionPart,hasClaimedStream = true,- hasAnswered = true,+ isStillAwaiting = true,+ hasOtherAwaitingCalls = false,hasPermission = true,- hasSubmittedForm = true,- hasOtherPendingAsks = false,}: BuildOptions = {}) => {const publishedEvents: Array<{ type: string }> = [];+ const threadRepository = {+ findOne: jest.fn().mockResolvedValue(thread),+ };const agentChatService = {findToolPart: jest.fn().mockResolvedValue(toolPart),- getWritableThread: jest+ findAwaitingToolParts: jest.fn()- .mockResolvedValue({ id: 'thread-id', activeStreamId: null }),- updateToolPartOutput: jest.fn().mockResolvedValue(undefined),+ .mockResolvedValue([+ ...(isStillAwaiting ? [toolPart] : []),+ ...(hasOtherAwaitingCalls ? [{ id: 'other-part-id' }] : []),+ ]),+ getWritableThread: jest.fn().mockResolvedValue(thread),+ recordToolCallAnswer: jest.fn().mockResolvedValue(undefined),addMessage: jest.fn().mockResolvedValue({ id: 'answer-message-id', turnId: 'answer-turn' }),+ closePendingToolCalls: jest.fn().mockResolvedValue(undefined),};const agentChatStreamingService = {reapDeadStream: jest.fn().mockResolvedValue(null),@@ -96,20 +103,16 @@ describe('AnswerAskService', () => {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),+ resumeAnsweredStep: jest.fn().mockResolvedValue(undefined),};+ const step = { id: 'step-id', type: 'AI_AGENT' };const workflowRunWorkspaceService = {- resolveStepAwaitingToolCall: jest- .fn()- .mockResolvedValue({ status: 'RESOLVED', stepId: 'step-id' }),+ findStepAwaitingAnswer: jest.fn().mockResolvedValue(step),endWorkflowRun: jest.fn().mockResolvedValue(undefined),+ getWorkflowRun: jest.fn().mockResolvedValue({+ state: { stepInfos: { 'step-id': { threadId: 'thread-id' } } },+ }),};const permissionsService = {userHasWorkspaceSettingPermission: jest@@ -140,12 +143,12 @@ describe('AnswerAskService', () => {}),};- const service = new AnswerAskService(+ const service = new ToolCallAnswerService(+ threadRepository as never,agentChatService as never,agentChatStreamingService as never,actorService as never,eventPublisherService as never,- inputAskWorkspaceService as never,workflowRunnerWorkspaceService as never,workflowRunWorkspaceService as never,permissionsService as never,@@ -173,9 +176,9 @@ describe('AnswerAskService', () => {return {service,+ step,agentChatService,agentChatStreamingService,- inputAskWorkspaceService,workflowRunnerWorkspaceService,workflowRunWorkspaceService,permissionsService,@@ -185,34 +188,33 @@ describe('AnswerAskService', () => {};};- it('treats an Ask the caller cannot read as not found', async () => {- const { service } = buildService({ inputAsk: null });+ it('treats a tool call it cannot find as not found', async () => {+ const { service } = buildService({ toolPart: null });await expect(service.answer(answerArguments)).rejects.toMatchObject({- code: 'ASK_NOT_FOUND',+ code: 'TOOL_CALL_NOT_FOUND',});});- it('refuses an Ask that is no longer pending before touching anything', async () => {+ it('refuses a call the conversation no longer waits on, before touching anything', async () => {const { service, agentChatStreamingService, agentChatService } =buildService({- inputAsk: { ...chatInputAsk, status: InputAskStatus.ANSWERED },+ thread: { ...waitingThread, pendingQuestionMessageId: 'later-id' },});await expect(service.answer(answerArguments)).rejects.toMatchObject({- code: 'ASK_NOT_PENDING',+ code: 'TOOL_CALL_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 () => {+ it('records the answer, stops waiting and resumes the stream, claimed only while the conversation waits on the call', async () => {const {service,agentChatService,agentChatStreamingService,- inputAskWorkspaceService,publishedEvents,} = buildService();@@ -220,16 +222,19 @@ describe('AnswerAskService', () => {expect(result).toEqual({streamId: expect.any(String),- threadId: 'thread-id',turnId: 'answer-turn',});- expect(inputAskWorkspaceService.answer).toHaveBeenCalledWith({+ expect(agentChatStreamingService.tryClaimStream).toHaveBeenCalledWith({+ threadId: 'thread-id',workspaceId: 'workspace-id',- key: { threadId: 'thread-id', toolCallId: 'tool-call-id' },- response: { answers: ANSWERS },+ streamId: result.streamId,+ where: { pendingQuestionMessageId: 'question-message-id' },});- expect(agentChatService.updateToolPartOutput).toHaveBeenCalledWith({+ expect(agentChatService.recordToolCallAnswer).toHaveBeenCalledWith({+ threadId: 'thread-id',+ messageId: 'question-message-id',partId: 'part-id',+ isLastAnswer: true,workspaceId: 'workspace-id',toolOutput: expect.objectContaining({result: {@@ -264,22 +269,16 @@ describe('AnswerAskService', () => {});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);+ const { service, agentChatService, agentChatStreamingService } =+ buildService({ hasOtherAwaitingCalls: true });- expect(result).toEqual({+ expect(await service.answer(answerArguments)).toEqual({streamId: null,- threadId: 'thread-id',turnId: 'answer-turn',});- expect(agentChatService.updateToolPartOutput).toHaveBeenCalled();- expect(agentChatService.addMessage).toHaveBeenCalled();+ expect(agentChatService.recordToolCallAnswer).toHaveBeenCalledWith(+ expect.objectContaining({ isLastAnswer: false }),+ );expect(agentChatStreamingService.enqueueResumeStream,).not.toHaveBeenCalled();@@ -288,10 +287,6 @@ describe('AnswerAskService', () => {'workspace-id',expect.any(String),);- expect(publishedEvents).toContainEqual({- type: 'tool-call-resolved',- toolCallId: 'tool-call-id',- });});it.each([@@ -304,42 +299,42 @@ describe('AnswerAskService', () => {{ 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();+ const { service, agentChatStreamingService } = buildService();await expect(service.answer({ ...answerArguments, response }),- ).rejects.toMatchObject({ code: 'INVALID_ASK_RESPONSE' });- expect(inputAskWorkspaceService.answer).not.toHaveBeenCalled();+ ).rejects.toMatchObject({ code: 'INVALID_TOOL_CALL_OUTPUT' });+ expect(agentChatStreamingService.tryClaimStream).not.toHaveBeenCalled();});it('refuses someone without the AI permission', async () => {- const { service, inputAskWorkspaceService } = buildService({+ const { service, agentChatStreamingService } = buildService({hasPermission: false,});await expect(service.answer(answerArguments)).rejects.toMatchObject({- code: 'ASK_ANSWER_FORBIDDEN',+ code: 'TOOL_CALL_RESOLUTION_FORBIDDEN',});- expect(inputAskWorkspaceService.answer).not.toHaveBeenCalled();+ expect(agentChatStreamingService.tryClaimStream).not.toHaveBeenCalled();});- it('refuses while another response holds the stream, without answering', async () => {- const { service, inputAskWorkspaceService } = buildService({+ it('refuses while another answer or response holds the conversation, recording nothing', async () => {+ const { service, agentChatService } = buildService({hasClaimedStream: false,});await expect(service.answer(answerArguments)).rejects.toMatchObject({- code: 'ASK_NOT_PENDING',+ code: 'TOOL_CALL_NOT_PENDING',});- expect(inputAskWorkspaceService.answer).not.toHaveBeenCalled();+ expect(agentChatService.recordToolCallAnswer).not.toHaveBeenCalled();});- it('releases the stream it claimed when another answer won the Ask', async () => {+ it('releases the conversation it claimed when an earlier answer already closed the call', async () => {const { service, agentChatStreamingService, agentChatService } =- buildService({ hasAnswered: false });+ buildService({ isStillAwaiting: false });await expect(service.answer(answerArguments)).rejects.toMatchObject({- code: 'ASK_NOT_PENDING',+ code: 'TOOL_CALL_NOT_PENDING',});const [[{ streamId: claimedStreamId }]] =@@ -350,7 +345,7 @@ describe('AnswerAskService', () => {'workspace-id',claimedStreamId,);- expect(agentChatService.updateToolPartOutput).not.toHaveBeenCalled();+ expect(agentChatService.recordToolCallAnswer).not.toHaveBeenCalled();expect(agentChatService.addMessage).not.toHaveBeenCalled();});@@ -379,17 +374,10 @@ describe('AnswerAskService', () => {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',@@ -397,13 +385,13 @@ describe('AnswerAskService', () => {toolOutput: { result: { status: 'pending', email: PROPOSED_EMAIL } },};- it('sends the edited email as the person only once the Ask is answered', async () => {+ it('sends the edited email as the person, only once the conversation is claimed', async () => {const {service,toolRegistryService,- inputAskWorkspaceService,+ agentChatStreamingService,agentChatService,- } = buildService({ inputAsk: emailInputAsk, toolPart: emailPart });+ } = buildService({ toolPart: emailPart });const editedEmail = { ...PROPOSED_EMAIL, subject: 'Your renewal' };// The email goes out as whoever answered, from their request.@@ -433,11 +421,11 @@ describe('AnswerAskService', () => {}),);expect(- inputAskWorkspaceService.answer.mock.invocationCallOrder[0],+ agentChatStreamingService.tryClaimStream.mock.invocationCallOrder[0],).toBeLessThan(toolRegistryService.resolveAndExecute.mock.invocationCallOrder[0],);- expect(agentChatService.updateToolPartOutput).toHaveBeenCalledWith(+ expect(agentChatService.recordToolCallAnswer).toHaveBeenCalledWith(expect.objectContaining({toolOutput: expect.objectContaining({success: true,@@ -452,7 +440,6 @@ describe('AnswerAskService', () => {it('sends nothing when the person discards the email', async () => {const { service, toolRegistryService, agentChatService } = buildService({- inputAsk: emailInputAsk,toolPart: emailPart,});@@ -462,7 +449,7 @@ describe('AnswerAskService', () => {});expect(toolRegistryService.resolveAndExecute).not.toHaveBeenCalled();- expect(agentChatService.updateToolPartOutput).toHaveBeenCalledWith(+ expect(agentChatService.recordToolCallAnswer).toHaveBeenCalledWith(expect.objectContaining({toolOutput: expect.objectContaining({result: expect.objectContaining({ status: 'discarded' }),@@ -471,11 +458,10 @@ describe('AnswerAskService', () => {);});- it('sends nothing when another answer already claimed the Ask', async () => {+ it('sends nothing when an earlier answer already closed the call', async () => {const { service, toolRegistryService } = buildService({- inputAsk: emailInputAsk,toolPart: emailPart,- hasAnswered: false,+ isStillAwaiting: false,});await expect(@@ -483,80 +469,105 @@ describe('AnswerAskService', () => {...answerArguments,response: { decision: 'send', email: PROPOSED_EMAIL },}),- ).rejects.toMatchObject({ code: 'ASK_NOT_PENDING' });+ ).rejects.toMatchObject({ code: 'TOOL_CALL_NOT_PENDING' });expect(toolRegistryService.resolveAndExecute).not.toHaveBeenCalled();});});- describe('a workflow agent step', () => {- const runInputAsk = {- ...chatInputAsk,- workflowRunId: 'workflow-run-id',- stepId: 'step-id',- };+ describe('a call in a workflow run', () => {+ const runThread = { ...waitingThread, workflowRunId: 'workflow-run-id' };- it('hands the answer to the run, with no chat stream', async () => {+ it('records the answer and hands it to the run, with no chat stream', async () => {const {service,+ step,+ agentChatService,+ agentChatStreamingService,workflowRunnerWorkspaceService,workflowRunWorkspaceService,- agentChatStreamingService,permissionsService,- publishedEvents,- } = buildService({ inputAsk: runInputAsk });+ } = buildService({ thread: runThread });expect(await service.answer(answerArguments)).toEqual({streamId: null,- threadId: null,- turnId: null,+ turnId: 'answer-turn',});expect(permissionsService.userHasWorkspaceSettingPermission,).toHaveBeenCalledWith(expect.objectContaining({ setting: 'WORKFLOWS' }));+ expect(agentChatService.getWritableThread).not.toHaveBeenCalled();+ expect(agentChatService.recordToolCallAnswer).toHaveBeenCalledWith(+ expect.objectContaining({ isLastAnswer: true }),+ );+ expect(agentChatStreamingService.releaseStreamClaim).toHaveBeenCalled();expect(- workflowRunWorkspaceService.resolveStepAwaitingToolCall,+ workflowRunnerWorkspaceService.resumeAnsweredStep,).toHaveBeenCalledWith({workspaceId: 'workspace-id',workflowRunId: 'workflow-run-id',+ step,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('resumes nothing while another call of the step waits', async () => {+ const { service, workflowRunnerWorkspaceService } = buildService({+ thread: runThread,+ hasOtherAwaitingCalls: true,});++ await service.answer(answerArguments);++ expect(+ workflowRunnerWorkspaceService.resumeAnsweredStep,+ ).not.toHaveBeenCalled();});- it('refuses an answer the run no longer waits for', async () => {+ it('refuses an answer the run no longer waits for, closing its calls instead', async () => {const {service,- workflowRunnerWorkspaceService,+ agentChatService,+ agentChatStreamingService,workflowRunWorkspaceService,- } = buildService({ inputAsk: runInputAsk });+ } = buildService({ thread: runThread });- workflowRunWorkspaceService.resolveStepAwaitingToolCall.mockResolvedValue(- { status: 'NOT_AWAITING' },+ workflowRunWorkspaceService.findStepAwaitingAnswer.mockResolvedValue(+ null,);await expect(service.answer(answerArguments)).rejects.toMatchObject({- code: 'ASK_NOT_PENDING',+ code: 'TOOL_CALL_NOT_PENDING',});+ expect(agentChatService.recordToolCallAnswer).not.toHaveBeenCalled();+ expect(agentChatService.closePendingToolCalls).toHaveBeenCalledWith({+ threadId: 'thread-id',+ messageId: 'question-message-id',+ workspaceId: 'workspace-id',+ });+ expect(agentChatStreamingService.releaseStreamClaim).toHaveBeenCalled();+ });++ it('fails the run when the answer is recorded but its message cannot be added', async () => {+ const {+ service,+ agentChatService,+ workflowRunnerWorkspaceService,+ workflowRunWorkspaceService,+ } = buildService({ thread: runThread });++ agentChatService.addMessage.mockRejectedValue(new Error('Write failed'));++ await expect(service.answer(answerArguments)).rejects.toThrow(+ 'Write failed',+ );expect(- workflowRunnerWorkspaceService.resumeAnsweredAgentStep,+ workflowRunnerWorkspaceService.resumeAnsweredStep,).not.toHaveBeenCalled();+ expect(workflowRunWorkspaceService.endWorkflowRun).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'FAILED' }),+ );});it('fails the run when the answered step cannot resume', async () => {@@ -564,9 +575,9 @@ describe('AnswerAskService', () => {service,workflowRunnerWorkspaceService,workflowRunWorkspaceService,- } = buildService({ inputAsk: runInputAsk });+ } = buildService({ thread: runThread });- workflowRunnerWorkspaceService.resumeAnsweredAgentStep.mockRejectedValue(+ workflowRunnerWorkspaceService.resumeAnsweredStep.mockRejectedValue(new Error('Queue unavailable'),);@@ -583,93 +594,123 @@ describe('AnswerAskService', () => {});it('treats a run the caller cannot read as not found', async () => {- const { service, workflowRunRepository, workflowRunWorkspaceService } =- buildService({ inputAsk: runInputAsk });+ const { service, workflowRunRepository, agentChatStreamingService } =+ buildService({ thread: runThread });workflowRunRepository.findOne.mockResolvedValue(null);await expect(service.answer(answerArguments)).rejects.toMatchObject({- code: 'ASK_NOT_FOUND',+ code: 'TOOL_CALL_NOT_FOUND',});- expect(- workflowRunWorkspaceService.resolveStepAwaitingToolCall,- ).not.toHaveBeenCalled();+ expect(agentChatStreamingService.tryClaimStream).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',- };+ describe('issued by a form step', () => {+ const formPart = {+ ...questionPart,+ toolName: 'request_form',+ toolInput: { fields: FORM_FIELDS },+ toolOutput: { result: { status: 'pending' } },+ };- it('submits the form step with the response', async () => {- const { service, workflowRunnerWorkspaceService } = buildService({- inputAsk: formInputAsk,- });+ it('hands the values to the run', async () => {+ const { service, workflowRunnerWorkspaceService } = buildService({+ thread: runThread,+ toolPart: formPart,+ });- expect(await service.answer({...answerArguments,+ toolCallId: 'step-id',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%' },+ });++ expect(+ workflowRunnerWorkspaceService.resumeAnsweredStep,+ ).toHaveBeenCalledWith(+ expect.objectContaining({ response: { discount: '20%' } }),+ );});- });- it('rejects a response naming a field the form does not have', async () => {- const { service, workflowRunnerWorkspaceService } = buildService({- inputAsk: formInputAsk,+ it('rejects a value for a field the form does not have', async () => {+ const { service, agentChatStreamingService } = buildService({+ thread: runThread,+ toolPart: formPart,+ });++ await expect(+ service.answer({ ...answerArguments, response: { price: 10 } }),+ ).rejects.toMatchObject({ code: 'INVALID_TOOL_CALL_OUTPUT' });+ expect(agentChatStreamingService.tryClaimStream).not.toHaveBeenCalled();});- await expect(- service.answer({ ...answerArguments, response: { price: 10 } }),- ).rejects.toMatchObject({ code: 'INVALID_ASK_RESPONSE' });- expect(- workflowRunnerWorkspaceService.submitFormStep,- ).not.toHaveBeenCalled();+ it('refuses someone without the Workflows permission', async () => {+ const { service, workflowRunnerWorkspaceService } = buildService({+ thread: runThread,+ toolPart: formPart,+ hasPermission: false,+ });++ await expect(+ service.answer({ ...answerArguments, response: { discount: '20%' } }),+ ).rejects.toMatchObject({ code: 'TOOL_CALL_RESOLUTION_FORBIDDEN' });+ expect(+ workflowRunnerWorkspaceService.resumeAnsweredStep,+ ).not.toHaveBeenCalled();+ });});+ });- it('refuses a submission the form no longer waits for', async () => {- const { service } = buildService({- inputAsk: formInputAsk,- hasSubmittedForm: false,+ describe('the deprecated entry points', () => {+ it('answers a form step through the call named after it in its conversation', async () => {+ const { service, agentChatService } = buildService({+ thread: { ...waitingThread, workflowRunId: 'workflow-run-id' },+ toolPart: {+ ...questionPart,+ toolName: 'request_form',+ toolInput: { fields: FORM_FIELDS },+ toolOutput: { result: { status: 'pending' } },+ },});- await expect(- service.answer({ ...answerArguments, response: { discount: '20%' } }),- ).rejects.toMatchObject({ code: 'ASK_NOT_PENDING' });+ await service.answerFormStep({+ workflowRunId: 'workflow-run-id',+ stepId: 'step-id',+ response: { discount: '20%' },+ userWorkspaceId: 'user-workspace-id',+ workspaceMemberId: 'member-id',+ workspace,+ });++ expect(agentChatService.findToolPart).toHaveBeenCalledWith({+ threadId: 'thread-id',+ toolCallId: 'step-id',+ workspaceId: 'workspace-id',+ });});- it('refuses someone without the Workflows permission', async () => {- const { service, workflowRunnerWorkspaceService } = buildService({- inputAsk: formInputAsk,- hasPermission: false,+ it('answers the questions a message asked', async () => {+ const { service, agentChatService } = buildService();++ agentChatService.findAwaitingToolParts.mockResolvedValueOnce([+ { ...questionPart, toolCallId: 'tool-call-id' },+ ]);++ await service.answerQuestionsOfMessage({+ threadId: 'thread-id',+ messageId: 'question-message-id',+ response: { answers: ANSWERS },+ userWorkspaceId: 'user-workspace-id',+ workspaceMemberId: 'member-id',+ workspace,});- await expect(- service.answer({ ...answerArguments, response: { discount: '20%' } }),- ).rejects.toMatchObject({ code: 'ASK_ANSWER_FORBIDDEN' });- expect(- workflowRunnerWorkspaceService.submitFormStep,- ).not.toHaveBeenCalled();+ expect(agentChatService.findToolPart).toHaveBeenCalledWith({+ threadId: 'thread-id',+ toolCallId: 'tool-call-id',+ workspaceId: 'workspace-id',+ });+ expect(agentChatService.recordToolCallAnswer).toHaveBeenCalled();});});});diff --git a/packages/twenty-server/src/modules/input-ask/answer-ask/services/answer-ask.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.tssimilarity index 52%rename from packages/twenty-server/src/modules/input-ask/answer-ask/services/answer-ask.service.tsrename to packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.tsindex 468556ac2e1..7408936a354 100644--- a/packages/twenty-server/src/modules/input-ask/answer-ask/services/answer-ask.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts@@ -1,5 +1,6 @@import { Injectable } from '@nestjs/common';+import { msg } from '@lingui/core/macro';import { generateId } from 'ai';import { ASK_QUESTIONS_TOOL_NAME } from 'twenty-shared/ai';import { PermissionFlagType } from 'twenty-shared/constants';@@ -11,7 +12,6 @@ import { ToolRegistryService } from 'src/engine/core-modules/tool-provider/serviimport { 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';@@ -21,27 +21,29 @@ import { AgentChatStreamingService } from 'src/engine/metadata-modules/ai/ai-chaimport { 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 { 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 {+ AiException,+ AiExceptionCode,+} from 'src/engine/metadata-modules/ai/ai.exception';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 { type WorkflowAction } 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 { WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service';-type AnswerAskArgs = {- askId: string;+type AnswerToolCallArgs = {+ threadId: string;+ toolCallId: string;response: Record<string, unknown>;modelId?: string;userWorkspaceId: string;@@ -49,38 +51,25 @@ type AnswerAskArgs = {workspace: WorkspaceEntity;};-type AnswerAskOutcome = {+type AnswerToolCallOutcome = {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.+// Every pause for a person is a pausing tool call in a conversation, a chat or+// a workflow run's, and each is answered here. An answer takes the+// conversation's stream claim, and only while the conversation still waits on+// the message that paused, so each call is answered once and only the last+// answer resumes what waits on them.@Injectable()-export class AnswerAskService {+export class ToolCallAnswerService {constructor(+ @InjectAgentHistoryRepository('agentChatThread')+ private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,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,@@ -91,229 +80,62 @@ export class AnswerAskService {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,- });+ async answer(args: AnswerToolCallArgs): Promise<AnswerToolCallOutcome> {+ const { threadId, toolCallId, userWorkspaceId, workspace } = args;+ const workspaceId = workspace.id;- if (!isDefined(inputAsk)) {- throw new InputAskException(- 'Ask not found',- InputAskExceptionCode.ASK_NOT_FOUND,+ const [thread, toolPart] = await Promise.all([+ this.threadRepository.findOne(workspaceId, {+ where: { id: threadId },+ select: [+ 'id',+ 'workflowRunId',+ 'activeStreamId',+ 'pendingQuestionMessageId',+ ],+ }),+ this.agentChatService.findToolPart({ threadId, toolCallId, workspaceId }),+ ]);+ const pausingToolCall = parsePausingToolCall(toolPart);++ if (+ !isDefined(thread) ||+ !isDefined(toolPart) ||+ !isDefined(pausingToolCall)+ ) {+ throw new AiException(+ 'The tool call to answer could not be found',+ AiExceptionCode.TOOL_CALL_NOT_FOUND,);}- if (inputAsk.status !== InputAskStatus.PENDING) {- throw this.notPending();- }+ const { workflowRunId } = thread;- if (isDefined(inputAsk.threadId) && isDefined(inputAsk.toolCallId)) {- const { threadId, toolCallId, workflowRunId } = inputAsk;- const toolPart = await this.agentChatService.findToolPart({- threadId,- toolCallId,+ if (isDefined(workflowRunId)) {+ await this.assertCanAnswerForWorkflowRun({+ userWorkspaceId,workspaceId,+ workflowRunId,});- 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({+ } else {+ await this.assertCanAnswerInChat({...args,- form: inputAsk.form,- workflowRunId: inputAsk.workflowRunId,- stepId: inputAsk.stepId,+ messageId: toolPart.messageId,});-- 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)) {+ if (thread.pendingQuestionMessageId !== toolPart.messageId) {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 validation = pausingToolCall.validate(args.response);- 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 (!validation.isValid) {+ throw new AiException(+ validation.errorMessage,+ AiExceptionCode.INVALID_TOOL_CALL_OUTPUT,);-- 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,@@ -327,45 +149,52 @@ export class AnswerAskService {threadId,workspaceId,streamId,+ where: { pendingQuestionMessageId: toolPart.messageId },});if (!hasClaimedStream) {- throw new InputAskException(- 'The conversation is still busy with another response',- InputAskExceptionCode.ASK_NOT_PENDING,+ throw new AiException(+ 'The conversation is busy with another answer or response',+ AiExceptionCode.TOOL_CALL_NOT_PENDING,+ { userFriendlyMessage: msg`This conversation is busy. Try again.` },);}- let hasAnswered = false;+ let step: WorkflowAction | null = null;+ let isLastAnswer: boolean;+ let answerText: string;try {- hasAnswered = await this.inputAskWorkspaceService.answer({- workspaceId,- key: { threadId, toolCallId },- response: output,- });- } finally {- if (!hasAnswered) {- await this.agentChatStreamingService.releaseStreamClaim(- threadId,+ const awaitingToolParts =+ await this.agentChatService.findAwaitingToolParts({+ messageId: toolPart.messageId,workspaceId,- streamId,- );+ });++ if (!awaitingToolParts.some((part) => part.id === toolPart.id)) {+ throw this.notPending();}- }- if (!hasAnswered) {- throw this.notPending();- }+ if (isDefined(workflowRunId)) {+ step = await this.workflowRunWorkspaceService.findStepAwaitingAnswer({+ threadId,+ workflowRunId,+ workspaceId,+ });- let turnId: string | null;- let hasOtherPendingAsks = false;+ if (!isDefined(step)) {+ await this.agentChatService.closePendingToolCalls({+ threadId,+ messageId: toolPart.messageId,+ workspaceId,+ });++ throw this.notPending();+ }+ }- // 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,+ output: validation.output,context: this.buildCompletionContext({workspaceId,userWorkspaceId,@@ -373,147 +202,155 @@ export class AnswerAskService {}),});- await this.agentChatService.updateToolPartOutput({+ isLastAnswer = awaitingToolParts.length === 1;++ await this.agentChatService.recordToolCallAnswer({+ threadId,+ messageId: toolPart.messageId,partId: toolPart.id,toolOutput: completion.toolResult,+ isLastAnswer,workspaceId,});+ answerText = completion.answerText;+ } catch (error) {+ await this.agentChatStreamingService.releaseStreamClaim(+ threadId,+ workspaceId,+ streamId,+ );++ throw error;+ }++ // The answer is recorded and cannot be given again, so from here a+ // failure fails the turn or the run, which can then be retried.+ try {const answerMessage = await this.agentChatService.addMessage({threadId,userWorkspaceId,uiMessage: {role: AgentMessageRole.USER,- parts: [{ type: 'text', text: completion.answerText }],+ parts: [{ type: 'text', text: answerText }],},workspaceId,});- turnId = answerMessage.turnId;+ await this.publishToolCallResolved({ threadId, toolCallId, workspaceId });- // 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) {+ // A run resumes in its own executor, and a conversation still waiting+ // on other calls resumes with the last of their answers.+ if (isDefined(step) || !isLastAnswer) {await this.agentChatStreamingService.releaseStreamClaim(threadId,workspaceId,streamId,);- } else {- await this.agentChatStreamingService.enqueueResumeStream({- threadId,- userWorkspaceId,- workspaceMemberId,- workspace,- turnId,- streamId,- modelId,- messageId: answerMessage.id,- });++ if (isLastAnswer && isDefined(workflowRunId) && isDefined(step)) {+ await this.workflowRunnerWorkspaceService.resumeAnsweredStep({+ workspaceId,+ workflowRunId,+ step,+ threadId,+ response: validation.output,+ });+ }++ return { streamId: null, turnId: answerMessage.turnId };}- } catch (error) {- const streamError = mapErrorToStreamError(error);- await this.agentChatStreamingService.releaseStreamClaim(+ await this.agentChatStreamingService.enqueueResumeStream({threadId,- workspaceId,+ userWorkspaceId,+ workspaceMemberId: args.workspaceMemberId,+ workspace,+ turnId: answerMessage.turnId,streamId,- {- lastStreamError: {- ...streamError,- failedAt: new Date().toISOString(),- },- },- );+ modelId: args.modelId,+ messageId: answerMessage.id,+ });- await this.eventPublisherService- .publish({- threadId,- workspaceId,- event: {- type: 'stream-error',- code: streamError.code,- message: streamError.message,- },- })- .catch(() => {});+ return { streamId, turnId: answerMessage.turnId };+ } catch (error) {+ await this.failAfterAnswer({+ threadId,+ workspaceId,+ streamId,+ workflowRunId,+ error,+ });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,+ // Behind submitFormStep, kept for clients built before answerToolCall: a+ // form step's call is named after the step, in the step's conversation.+ async answerFormStep({workflowRunId,- }: ToolCallToAnswer & { workflowRunId: string }): Promise<void> {- const workspaceId = workspace.id;-- await this.assertCanAnswerForWorkflowRun({- userWorkspaceId,- workspaceId,+ stepId,+ ...args+ }: Omit<AnswerToolCallArgs, 'threadId' | 'toolCallId' | 'modelId'> & {+ workflowRunId: string;+ stepId: string;+ }): Promise<void> {+ const workflowRun = await this.workflowRunWorkspaceService.getWorkflowRun({workflowRunId,+ workspaceId: args.workspace.id,});+ const threadId = workflowRun?.state?.stepInfos?.[stepId]?.threadId;- // 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 (!isDefined(threadId)) {+ throw this.notPending();+ }++ await this.answer({ ...args, threadId, toolCallId: stepId });+ }- if (claim.status !== 'RESOLVED') {+ // Behind answerAgentChatQuestion, kept for clients built before+ // answerToolCall: a question is named by the message that asked it.+ async answerQuestionsOfMessage({+ messageId,+ ...args+ }: Omit<AnswerToolCallArgs, 'toolCallId'> & {+ messageId: string;+ }): Promise<AnswerToolCallOutcome> {+ const awaitingToolParts = await this.agentChatService.findAwaitingToolParts(+ { messageId, workspaceId: args.workspace.id },+ );+ const questionsPart = awaitingToolParts.find(+ (part) => part.toolName === ASK_QUESTIONS_TOOL_NAME,+ );++ if (!isDefined(questionsPart?.toolCallId)) {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,- }),- });+ return this.answer({ ...args, toolCallId: questionsPart.toolCallId });+ }- await this.workflowRunnerWorkspaceService.resumeAnsweredAgentStep({- workspaceId,- workflowRunId,- stepId: claim.stepId,+ private async failAfterAnswer({+ threadId,+ workspaceId,+ streamId,+ workflowRunId,+ error,+ }: {+ threadId: string;+ workspaceId: string;+ streamId: string;+ workflowRunId: string | null;+ error: unknown;+ }): Promise<void> {+ if (isDefined(workflowRunId)) {+ await this.agentChatStreamingService.releaseStreamClaim(threadId,- toolPart,- toolResult: completion.toolResult,- answerText: completion.answerText,- senderUserWorkspaceId: userWorkspaceId,- });- } catch (error) {+ workspaceId,+ streamId,+ );+await this.workflowRunWorkspaceService.endWorkflowRun({workflowRunId,workspaceId,@@ -521,10 +358,63 @@ export class AnswerAskService {error: 'The run could not resume after its question was answered',});- throw error;+ return;}- await this.publishToolCallResolved({ threadId, toolCallId, workspaceId });+ 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(() => {});+ }++ private async assertCanAnswerInChat({+ threadId,+ messageId,+ modelId,+ userWorkspaceId,+ workspaceMemberId,+ workspace,+ }: AnswerToolCallArgs & { messageId: string }): Promise<void> {+ await this.assertHasSettingPermission({+ setting: PermissionFlagType.AI,+ userWorkspaceId,+ workspaceId: workspace.id,+ });++ await this.turnPreflightService.assertCanStartChatTurn({+ threadId,+ modelId,+ userWorkspaceId,+ workspaceMemberId,+ workspace,+ });++ await this.actorService.authorizeToolCallResolution({+ workspaceId: workspace.id,+ threadId,+ messageId,+ });}// The same permission that lets someone run a workflow, on a run they can@@ -562,9 +452,9 @@ export class AnswerAskService {}if (!isDefined(workflowRun)) {- throw new InputAskException(- 'Ask not found',- InputAskExceptionCode.ASK_NOT_FOUND,+ throw new AiException(+ 'The tool call to answer could not be found',+ AiExceptionCode.TOOL_CALL_NOT_FOUND,);}}@@ -585,9 +475,9 @@ export class AnswerAskService {const authContext = workspaceAuthContextStorage.getStore();if (!isDefined(authContext) || !isUserAuthContext(authContext)) {- throw new InputAskException(+ throw new AiException('Answering requires a signed-in person',- InputAskExceptionCode.ASK_ANSWER_FORBIDDEN,+ AiExceptionCode.TOOL_CALL_RESOLUTION_FORBIDDEN,);}@@ -645,17 +535,17 @@ export class AnswerAskService {});if (!hasPermission) {- throw new InputAskException(- `Answering this Ask requires the ${setting} permission`,- InputAskExceptionCode.ASK_ANSWER_FORBIDDEN,+ throw new AiException(+ `Answering this request requires the ${setting} permission`,+ AiExceptionCode.TOOL_CALL_RESOLUTION_FORBIDDEN,);}}- private notPending(): InputAskException {- return new InputAskException(- 'This Ask is no longer waiting for an answer',- InputAskExceptionCode.ASK_NOT_PENDING,+ private notPending(): AiException {+ return new AiException(+ 'This tool call is no longer waiting for an answer',+ AiExceptionCode.TOOL_CALL_NOT_PENDING,);}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.tsindex f365327380d..0f3c9a1c1f8 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@@ -17,6 +17,8 @@ export enum AiExceptionCode {INVALID_CHAT_THREAD_TITLE = 'INVALID_CHAT_THREAD_TITLE',MESSAGE_NOT_FOUND = 'MESSAGE_NOT_FOUND',INVALID_TOOL_CALL_OUTPUT = 'INVALID_TOOL_CALL_OUTPUT',+ TOOL_CALL_NOT_FOUND = 'TOOL_CALL_NOT_FOUND',+ TOOL_CALL_NOT_PENDING = 'TOOL_CALL_NOT_PENDING',API_KEY_NOT_CONFIGURED = 'API_KEY_NOT_CONFIGURED',USER_WORKSPACE_ID_NOT_FOUND = 'USER_WORKSPACE_ID_NOT_FOUND',ROLE_NOT_FOUND = 'ROLE_NOT_FOUND',@@ -59,6 +61,10 @@ const getAiExceptionUserFriendlyMessage = (code: AiExceptionCode) => {return msg`Chat message not found.`;case AiExceptionCode.INVALID_TOOL_CALL_OUTPUT:return msg`Invalid answer for this request.`;+ case AiExceptionCode.TOOL_CALL_NOT_FOUND:+ return msg`This request for input could not be found.`;+ case AiExceptionCode.TOOL_CALL_NOT_PENDING:+ return msg`This request is no longer waiting for an answer.`;case AiExceptionCode.API_KEY_NOT_CONFIGURED:return msg`API key is not configured.`;case AiExceptionCode.USER_WORKSPACE_ID_NOT_FOUND: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.tsindex ae4a17de95c..63ceaf62917 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@@ -20,6 +20,7 @@ export const aiGraphqlApiExceptionHandler = (error: Error) => {case AiExceptionCode.RECORD_NOT_FOUND:case AiExceptionCode.WORKSPACE_NOT_FOUND:case AiExceptionCode.MESSAGE_NOT_FOUND:+ case AiExceptionCode.TOOL_CALL_NOT_FOUND:case AiExceptionCode.ROLE_NOT_FOUND:case AiExceptionCode.RUN_AS_WORKSPACE_MEMBER_NOT_FOUND:case AiExceptionCode.EVALUATION_MODEL_NOT_FOUND:@@ -28,6 +29,7 @@ export const aiGraphqlApiExceptionHandler = (error: Error) => {case AiExceptionCode.INVALID_AGENT_INPUT:case AiExceptionCode.INVALID_CHAT_THREAD_TITLE:case AiExceptionCode.INVALID_TOOL_CALL_OUTPUT:+ case AiExceptionCode.TOOL_CALL_NOT_PENDING:case AiExceptionCode.EVALUATION_QUESTION_UNSUPPORTED:case AiExceptionCode.INVALID_EVALUATION_REQUEST:throw new UserInputError(error);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.tsindex afb9db89ef1..8dc194e5c47 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@@ -64,12 +64,14 @@ export const APPLE_AGENT_CHAT_CONVERSATION_SEEDS: AgentChatConversationSeed[] =},];-// Conversations paused on, or already past, a question or an email for Tim's+// Conversations paused on, or already past, a question, an email or a form for Tim's// team to decide on.-export const AGENT_CHAT_INPUT_ASK_THREAD_DATA_SEED_IDS = {+export const AGENT_CHAT_PENDING_INPUT_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',+ PENDING_FORM: '20202020-0000-4000-8000-00000000001a',+ ANSWERED_FORM: '20202020-0000-4000-8000-00000000001b',};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-pending-input.workspace-service.tssimilarity index 83%rename from packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-input-ask.workspace-service.tsrename to packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.workspace-service.tsindex 6f076fa73ec..a9f5166f39c 100644--- 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-pending-input.workspace-service.ts@@ -6,9 +6,12 @@ import {type ExtendedUIMessagePart,PROPOSE_EMAIL_TOOL_NAME,type ProposedEmail,+ REQUEST_FORM_TOOL_NAME,+ type RequestFormField,} from 'twenty-shared/ai';import { STANDARD_OBJECTS } from 'twenty-shared/metadata';import {+ FieldMetadataType,RecordShareAccessLevel,RecordSharePrincipalType,RecordShareRowCause,@@ -26,18 +29,18 @@ import { mapAiStepsToUiMessageParts } from 'src/engine/metadata-modules/ai/ai-agimport { mapUIMessagePartsToDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/mapUIMessagePartsToDBParts';import { createAskQuestionsTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool';import { createProposeEmailTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/propose-email.tool';+import { createRequestFormTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool';import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';import { 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 { AGENT_CHAT_PENDING_INPUT_THREAD_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/constants/agent-chat-seeds.constant';import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';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 =+const AGENT_CHAT_PENDING_INPUT_SEED_NAMESPACE ='3c7e1f52-8a4d-4b0e-9d61-2f5a7c9e0b14';const MEMBERS = {@@ -134,6 +137,51 @@ export const askQuestionsCall = (}),});+export const requestFormCall = (+ fields: RequestFormField[],+): SeededToolCall => ({+ toolName: REQUEST_FORM_TOOL_NAME,+ input: { fields },+ buildPendingOutput: () => createRequestFormTool().execute({ fields }),+});++const AIRBNB_EXPANSION_FIELDS: RequestFormField[] = [+ {+ name: 'company',+ label: 'Company',+ type: 'RECORD',+ settings: { objectName: 'company' },+ },+ {+ name: 'amount',+ label: 'Amount (USD)',+ type: FieldMetadataType.NUMBER,+ placeholder: '50000',+ },+ { name: 'closeDate', label: 'Expected close', type: FieldMetadataType.DATE },+ {+ name: 'nextStep',+ label: 'Next step',+ type: FieldMetadataType.TEXT,+ placeholder: 'Security review with their IT team',+ },+];++const FIGMA_CALL_FIELDS: RequestFormField[] = [+ { name: 'callDate', label: 'Call date', type: FieldMetadataType.DATE },+ {+ name: 'attendees',+ label: 'Attendees on their side',+ type: FieldMetadataType.NUMBER,+ },+ {+ name: 'summary',+ label: 'Summary',+ type: FieldMetadataType.TEXT,+ placeholder: 'What was decided',+ },+];+const LINEAR_WELCOME_EMAIL: ProposedEmail = {recipients: { to: '[email protected]', cc: '', bcc: '' },subject: 'Welcome to Twenty, Linear',@@ -152,7 +200,7 @@ type ConversationToSeed = {askedBy: Member;prompt: string;intro: string;- // Calls made in the same step, each waiting on its own Ask.+ // Calls made in the same step, each waiting on its own answer.calls: SeededToolCall[];// Answers the first call, in a conversation that made only one.answer?: {@@ -164,7 +212,7 @@ type ConversationToSeed = {const CONVERSATIONS_TO_SEED: ConversationToSeed[] = [{- threadId: AGENT_CHAT_INPUT_ASK_THREAD_DATA_SEED_IDS.PENDING_QUESTIONS,+ threadId: AGENT_CHAT_PENDING_INPUT_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.',@@ -172,7 +220,8 @@ const CONVERSATIONS_TO_SEED: ConversationToSeed[] = [calls: [askQuestionsCall(WEBINAR_QUESTIONS)],},{- threadId: AGENT_CHAT_INPUT_ASK_THREAD_DATA_SEED_IDS.PENDING_EMAIL_APPROVAL,+ threadId:+ AGENT_CHAT_PENDING_INPUT_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.',@@ -184,7 +233,7 @@ const CONVERSATIONS_TO_SEED: ConversationToSeed[] = [},},{- threadId: AGENT_CHAT_INPUT_ASK_THREAD_DATA_SEED_IDS.SENT_EMAIL_APPROVAL,+ threadId: AGENT_CHAT_PENDING_INPUT_THREAD_DATA_SEED_IDS.SENT_EMAIL_APPROVAL,title: 'Send the renewal quote to Stripe',askedBy: 'TIM',prompt: 'Send Stripe their renewal quote for 2027.',@@ -207,7 +256,7 @@ const CONVERSATIONS_TO_SEED: ConversationToSeed[] = [sharedWith: { member: 'PHIL', accessLevel: RecordShareAccessLevel.READ },},{- threadId: AGENT_CHAT_INPUT_ASK_THREAD_DATA_SEED_IDS.ANSWERED_QUESTION,+ threadId: AGENT_CHAT_PENDING_INPUT_THREAD_DATA_SEED_IDS.ANSWERED_QUESTION,title: 'Assign the Linear onboarding',askedBy: 'TIM',prompt: 'Linear signed. Set up their onboarding.',@@ -223,7 +272,8 @@ const CONVERSATIONS_TO_SEED: ConversationToSeed[] = [sharedWith: { member: 'PHIL', accessLevel: RecordShareAccessLevel.READ },},{- threadId: AGENT_CHAT_INPUT_ASK_THREAD_DATA_SEED_IDS.PENDING_EMAIL_APPROVALS,+ threadId:+ AGENT_CHAT_PENDING_INPUT_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.',@@ -233,14 +283,38 @@ const CONVERSATIONS_TO_SEED: ConversationToSeed[] = [proposeEmailCall(FIGMA_WELCOME_EMAIL),],},+ {+ threadId: AGENT_CHAT_PENDING_INPUT_THREAD_DATA_SEED_IDS.PENDING_FORM,+ title: 'Open the Airbnb expansion deal',+ askedBy: 'TIM',+ prompt: 'Airbnb wants to roll Twenty out to their EMEA team. Log the deal.',+ intro: 'Fill in the deal details and I will create the opportunity:',+ calls: [requestFormCall(AIRBNB_EXPANSION_FIELDS)],+ },+ {+ threadId: AGENT_CHAT_PENDING_INPUT_THREAD_DATA_SEED_IDS.ANSWERED_FORM,+ title: 'Log the Figma kickoff call',+ askedBy: 'TIM',+ prompt: 'Log my kickoff call with Figma.',+ intro: 'A few details about the call:',+ calls: [requestFormCall(FIGMA_CALL_FIELDS)],+ answer: {+ response: {+ callDate: '2026-09-29',+ attendees: 4,+ summary: 'Pipeline import first, SSO the week after.',+ },+ reply:+ 'Logged the call on Figma with a note. I also created a task for Phil to schedule the SSO setup next week.',+ },+ },];-// Seeds Tim's conversations that wait on a question or an email, or have+// Seeds Tim's conversations that wait on a question, an email or a form, 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.+// calling a model.@Injectable()-export class DevSeederAgentChatInputAskWorkspaceService {+export class DevSeederAgentChatPendingInputWorkspaceService {constructor(@InjectAgentHistoryRepository('agentChatThread')private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,@@ -250,7 +324,6 @@ export class DevSeederAgentChatInputAskWorkspaceService {private readonly messageRepository: AgentHistoryRepository<AgentMessageWorkspaceEntity>,@InjectAgentHistoryRepository('agentMessagePart')private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartEntity>,- private readonly inputAskWorkspaceService: InputAskWorkspaceService,private readonly recordShareStorageService: RecordShareStorageService,private readonly workspaceCacheService: WorkspaceCacheService,) {}@@ -277,7 +350,7 @@ export class DevSeederAgentChatInputAskWorkspaceService {const seedId = (name: string) =>v5(`${conversation.threadId}:${name}`,- AGENT_CHAT_INPUT_ASK_SEED_NAMESPACE,+ AGENT_CHAT_PENDING_INPUT_SEED_NAMESPACE,);const { threadId } = conversation;const askedBy = MEMBERS[conversation.askedBy];@@ -307,6 +380,9 @@ export class DevSeederAgentChatInputAskWorkspaceService {title: conversation.title,workspaceMemberId: MEMBERS.TIM.workspaceMemberId,userWorkspaceId: MEMBERS.TIM.userWorkspaceId,+ pendingQuestionMessageId: isDefined(conversation.answer)+ ? null+ : seedId('assistantMessage'),});const questionTurnId = seedId('questionTurn');@@ -374,28 +450,10 @@ export class DevSeederAgentChatInputAskWorkspaceService {]),});- 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, {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-pending-input.workspace-service.tssimilarity index 77%rename from packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-input-ask.workspace-service.tsrename to packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.tsindex 55267b980e2..7dab5a62cd6 100644--- 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-pending-input.workspace-service.ts@@ -1,6 +1,10 @@import { Injectable } from '@nestjs/common';-import { type AskQuestionItem, type ProposedEmail } from 'twenty-shared/ai';+import {+ type AskQuestionItem,+ type ProposedEmail,+ REQUEST_FORM_TOOL_NAME,+} from 'twenty-shared/ai';import {type ActorMetadata,FieldActorSource,@@ -15,6 +19,11 @@ import {WorkflowVersionStatus,} from 'src/engine/core-modules/workflow/entities/workflow-version.entity';import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';+import { PAUSING_TOOLS } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant';+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 AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-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';@@ -24,14 +33,13 @@ import {askQuestionsCall,proposeEmailCall,type SeededToolCall,-} from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-input-ask.workspace-service';+} from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.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,@@ -43,11 +51,11 @@ import {WorkflowTriggerType,} from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';-const WORKFLOW_INPUT_ASK_SEED_NAMESPACE =+const WORKFLOW_PENDING_INPUT_SEED_NAMESPACE ='6f0a9a3e-2b1f-4c55-9f0b-7c1d2e3f4a5b';const seedId = (name: string, workspaceId: string) =>- v5(`${name}:${workspaceId}`, WORKFLOW_INPUT_ASK_SEED_NAMESPACE);+ v5(`${name}:${workspaceId}`, WORKFLOW_PENDING_INPUT_SEED_NAMESPACE);const SYSTEM_ACTOR: ActorMetadata = {source: FieldActorSource.SYSTEM,@@ -194,11 +202,15 @@ type SeededWorkflow = {};// 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.+// the run view, the paused conversations and every kind of card can be tried+// without calling a model.@Injectable()-export class DevSeederWorkflowInputAskWorkspaceService {+export class DevSeederWorkflowPendingInputWorkspaceService {constructor(+ @InjectAgentHistoryRepository('agentChatThread')+ private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,+ @InjectAgentHistoryRepository('agentMessagePart')+ private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartWorkspaceEntity>,private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,private readonly workflowAgentConversationService: WorkflowAgentConversationWorkspaceService,private readonly workspaceOrmManager: WorkspaceOrmManager,@@ -252,35 +264,33 @@ export class DevSeederWorkflowInputAskWorkspaceService {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,+ recordConversation: () =>+ 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,+ },+ ],+ },+ ],+ },+ }),});}@@ -333,22 +343,30 @@ export class DevSeederWorkflowInputAskWorkspaceService {workflowRunId,workflow: discountWorkflow,initiator: discountRun.initiator,- recordPendingAsks: async () => [- {- name: formStep.name,- form: { kind: 'formFields', fields: formStep.settings.input },- },- ],+ recordConversation: () =>+ this.workflowAgentConversationService.recordFormRequest({+ workspaceId,+ workflowRunId,+ stepId: formStep.id,+ title: formStep.name,+ fields: formStep.settings.input,+ }),});if (isDefined(discountRun.response)) {+ await this.recordFormAnswer({+ workspaceId,+ workflowRunId,+ formStep,+ response: discountRun.response,+ });+await this.workflowRunWorkspaceService.updateStepInfoIfPending({stepId: formStep.id,stepInfo: {status: StepStatus.SUCCESS,result: discountRun.response,},- inputAskResponse: discountRun.response,workflowRunId,workspaceId,});@@ -365,19 +383,19 @@ export class DevSeederWorkflowInputAskWorkspaceService {}// 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.+ // person, once its conversation is recorded.private async seedPausedRun({workspaceId,workflowRunId,workflow,initiator,- recordPendingAsks,+ recordConversation,}: {workspaceId: string;workflowRunId: string;workflow: SeededWorkflow;initiator: Initiator;- recordPendingAsks: () => Promise<WorkflowPendingAsk[] | undefined>;+ recordConversation: () => Promise<unknown>;}): Promise<void> {await this.workflowRunWorkspaceService.createCoreWorkflowRun({workflowRunId,@@ -403,15 +421,57 @@ export class DevSeederWorkflowInputAskWorkspaceService {workspaceId,});+ await recordConversation();+await this.workflowRunWorkspaceService.updateWorkflowRunStepInfo({stepId: workflow.step.id,stepInfo: { status: StepStatus.PENDING },- pendingAsks: await recordPendingAsks(),workflowRunId,workspaceId,});}+ // Records the answer in the form's conversation as answering it would,+ // without resuming the run.+ private async recordFormAnswer({+ workspaceId,+ workflowRunId,+ formStep,+ response,+ }: {+ workspaceId: string;+ workflowRunId: string;+ formStep: WorkflowFormAction;+ response: Record<string, unknown>;+ }): Promise<void> {+ const thread = await this.threadRepository.findOneOrFail(workspaceId, {+ where: { workflowRunId },+ select: ['id', 'pendingQuestionMessageId'],+ });+ const completion = await PAUSING_TOOLS.get(REQUEST_FORM_TOOL_NAME)+ ?.parseCall({ fields: formStep.settings.input })+ ?.complete({+ output: response,+ context: { executeTool: async () => ({ success: true, message: '' }) },+ });++ if (!isDefined(thread.pendingQuestionMessageId) || !isDefined(completion)) {+ throw new Error('Seeded form call does not parse');+ }++ await this.messagePartRepository.update(+ workspaceId,+ { messageId: thread.pendingQuestionMessageId, toolCallId: formStep.id },+ { toolOutput: completion.toolResult },+ );++ await this.threadRepository.update(+ workspaceId,+ { id: thread.id },+ { pendingQuestionMessageId: null },+ );+ }+private async insertWorkflow({workspaceId,applicationId,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.tsindex 99f3f817a11..39172d891b8 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@@ -30,11 +30,10 @@ 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 { DevSeederAgentChatPendingInputWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.workspace-service';import { DevSeederDataService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-data.service';-import { DevSeederWorkflowInputAskWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-input-ask.workspace-service';+import { DevSeederWorkflowPendingInputWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.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';@@ -79,7 +78,6 @@ import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflowUpgradeModule,WorkflowRunModule,WorkflowAgentConversationModule,- InputAskModule,RecordShareStorageModule,],exports: [DevSeederWorkspaceService],@@ -89,8 +87,8 @@ import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflowDevSeederPermissionsService,DevSeederDataService,TimelineActivitySeederService,- DevSeederWorkflowInputAskWorkspaceService,- DevSeederAgentChatInputAskWorkspaceService,+ DevSeederWorkflowPendingInputWorkspaceService,+ DevSeederAgentChatPendingInputWorkspaceService,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.tsindex c56376bdcdd..f1497952f83 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,9 +48,9 @@ import { seedUnsubscribeTopics } from 'src/engine/workspace-manager/dev-seeder/cimport { 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 { DevSeederAgentChatPendingInputWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.workspace-service';import { DevSeederDataService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-data.service';-import { DevSeederWorkflowInputAskWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-input-ask.workspace-service';+import { DevSeederWorkflowPendingInputWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.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';@@ -71,8 +71,8 @@ export class DevSeederWorkspaceService {private readonly devSeederMetadataService: DevSeederMetadataService,private readonly devSeederPermissionsService: DevSeederPermissionsService,private readonly devSeederDataService: DevSeederDataService,- private readonly devSeederWorkflowInputAskService: DevSeederWorkflowInputAskWorkspaceService,- private readonly devSeederAgentChatInputAskService: DevSeederAgentChatInputAskWorkspaceService,+ private readonly devSeederWorkflowPendingInputService: DevSeederWorkflowPendingInputWorkspaceService,+ private readonly devSeederAgentChatPendingInputService: DevSeederAgentChatPendingInputWorkspaceService,private readonly applicationService: ApplicationService,private readonly applicationRegistrationService: ApplicationRegistrationService,private readonly workspaceCacheService: WorkspaceCacheService,@@ -229,7 +229,7 @@ export class DevSeederWorkspaceService {});// Before the chat seed, whose owner grants then cover these threads too.- await this.devSeederAgentChatInputAskService.seed({ workspaceId });+ await this.devSeederAgentChatPendingInputService.seed({ workspaceId });await this.seedAgentChat({workspaceId,@@ -241,7 +241,7 @@ export class DevSeederWorkspaceService {},});- await this.devSeederWorkflowInputAskService.seed({+ await this.devSeederWorkflowPendingInputService.seed({workspaceId,applicationId: workspaceCustomFlatApplication.id,});diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/search-fields-by-standard-object-name.constant.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/search-fields-by-standard-object-name.constant.tsindex a83032daf65..765590d1669 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/search-fields-by-standard-object-name.constant.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/search-fields-by-standard-object-name.constant.ts@@ -70,7 +70,6 @@ export const SEARCH_FIELDS_BY_STANDARD_OBJECT_NAME = {{ name: 'name', type: FieldMetadataType.FULL_NAME },{ name: 'userEmail', type: FieldMetadataType.TEXT },],- inputAsk: [{ name: 'name', type: FieldMetadataType.TEXT }],} satisfies {[ObjectName in AllStandardObjectName]: {name: AllStandardObjectFieldName<ObjectName>;diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snap b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snapindex 362f96f25d7..ecd11825ee0 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snap+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snap@@ -5,307 +5,304 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"agentChatThread": {"fields": {"activeStreamId": {- "id": "00000000-0000-0000-0000-000000001032",+ "id": "00000000-0000-0000-0000-000000001030",},"archivedAt": {- "id": "00000000-0000-0000-0000-000000001020",+ "id": "00000000-0000-0000-0000-000000001018",},"attachments": {- "id": "00000000-0000-0000-0000-000000001038",+ "id": "00000000-0000-0000-0000-000000001036",},"contextWindowTokens": {- "id": "00000000-0000-0000-0000-000000001026",+ "id": "00000000-0000-0000-0000-000000001024",},"conversationSize": {- "id": "00000000-0000-0000-0000-000000001027",+ "id": "00000000-0000-0000-0000-000000001025",},"createdAt": {- "id": "00000000-0000-0000-0000-000000001017",+ "id": "00000000-0000-0000-0000-000000001015",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001019",+ "id": "00000000-0000-0000-0000-000000001017",},"id": {- "id": "00000000-0000-0000-0000-000000001016",- },- "inputAsks": {- "id": "00000000-0000-0000-0000-000000001040",+ "id": "00000000-0000-0000-0000-000000001014",},"lastStreamError": {- "id": "00000000-0000-0000-0000-000000001035",+ "id": "00000000-0000-0000-0000-000000001033",},"messages": {- "id": "00000000-0000-0000-0000-000000001037",+ "id": "00000000-0000-0000-0000-000000001035",},"pendingQuestionMessageId": {- "id": "00000000-0000-0000-0000-000000001034",+ "id": "00000000-0000-0000-0000-000000001032",},"recordTargets": {- "id": "00000000-0000-0000-0000-000000001039",+ "id": "00000000-0000-0000-0000-000000001037",},"title": {- "id": "00000000-0000-0000-0000-000000001023",+ "id": "00000000-0000-0000-0000-000000001021",},"totalCacheCreationTokens": {- "id": "00000000-0000-0000-0000-000000001031",+ "id": "00000000-0000-0000-0000-000000001029",},"totalCacheReadTokens": {- "id": "00000000-0000-0000-0000-000000001030",+ "id": "00000000-0000-0000-0000-000000001028",},"totalInputCredits": {- "id": "00000000-0000-0000-0000-000000001028",+ "id": "00000000-0000-0000-0000-000000001026",},"totalInputTokens": {- "id": "00000000-0000-0000-0000-000000001024",+ "id": "00000000-0000-0000-0000-000000001022",},"totalOutputCredits": {- "id": "00000000-0000-0000-0000-000000001029",+ "id": "00000000-0000-0000-0000-000000001027",},"totalOutputTokens": {- "id": "00000000-0000-0000-0000-000000001025",+ "id": "00000000-0000-0000-0000-000000001023",},"turns": {- "id": "00000000-0000-0000-0000-000000001036",+ "id": "00000000-0000-0000-0000-000000001034",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001018",+ "id": "00000000-0000-0000-0000-000000001016",},"userWorkspaceId": {- "id": "00000000-0000-0000-0000-000000001021",+ "id": "00000000-0000-0000-0000-000000001019",},"workflowRun": {- "id": "00000000-0000-0000-0000-000000001033",+ "id": "00000000-0000-0000-0000-000000001031",},"workspaceMember": {- "id": "00000000-0000-0000-0000-000000001022",+ "id": "00000000-0000-0000-0000-000000001020",},},- "id": "00000000-0000-0000-0000-000000001041",+ "id": "00000000-0000-0000-0000-000000001038","views": undefined,},"agentChatThreadTarget": {"fields": {"createdAt": {- "id": "00000000-0000-0000-0000-000000001043",+ "id": "00000000-0000-0000-0000-000000001040",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001045",+ "id": "00000000-0000-0000-0000-000000001042",},"id": {- "id": "00000000-0000-0000-0000-000000001042",+ "id": "00000000-0000-0000-0000-000000001039",},"targetCompany": {- "id": "00000000-0000-0000-0000-000000001048",+ "id": "00000000-0000-0000-0000-000000001045",},"targetOpportunity": {- "id": "00000000-0000-0000-0000-000000001049",+ "id": "00000000-0000-0000-0000-000000001046",},"targetPerson": {- "id": "00000000-0000-0000-0000-000000001047",+ "id": "00000000-0000-0000-0000-000000001044",},"thread": {- "id": "00000000-0000-0000-0000-000000001046",+ "id": "00000000-0000-0000-0000-000000001043",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001044",+ "id": "00000000-0000-0000-0000-000000001041",},},- "id": "00000000-0000-0000-0000-000000001050",+ "id": "00000000-0000-0000-0000-000000001047","views": {},},"agentMessage": {"fields": {"agentId": {- "id": "00000000-0000-0000-0000-000000001064",+ "id": "00000000-0000-0000-0000-000000001061",},"createdAt": {- "id": "00000000-0000-0000-0000-000000001061",+ "id": "00000000-0000-0000-0000-000000001058",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001063",+ "id": "00000000-0000-0000-0000-000000001060",},"id": {- "id": "00000000-0000-0000-0000-000000001060",+ "id": "00000000-0000-0000-0000-000000001057",},"isHidden": {- "id": "00000000-0000-0000-0000-000000001070",+ "id": "00000000-0000-0000-0000-000000001067",},"parts": {- "id": "00000000-0000-0000-0000-000000001074",+ "id": "00000000-0000-0000-0000-000000001071",},"processedAt": {- "id": "00000000-0000-0000-0000-000000001071",+ "id": "00000000-0000-0000-0000-000000001068",},"role": {- "id": "00000000-0000-0000-0000-000000001068",+ "id": "00000000-0000-0000-0000-000000001065",},"senderApplicationId": {- "id": "00000000-0000-0000-0000-000000001067",+ "id": "00000000-0000-0000-0000-000000001064",},"senderUserWorkspaceId": {- "id": "00000000-0000-0000-0000-000000001066",+ "id": "00000000-0000-0000-0000-000000001063",},"senderWorkspaceMember": {- "id": "00000000-0000-0000-0000-000000001065",+ "id": "00000000-0000-0000-0000-000000001062",},"status": {- "id": "00000000-0000-0000-0000-000000001069",+ "id": "00000000-0000-0000-0000-000000001066",},"thread": {- "id": "00000000-0000-0000-0000-000000001072",+ "id": "00000000-0000-0000-0000-000000001069",},"turn": {- "id": "00000000-0000-0000-0000-000000001073",+ "id": "00000000-0000-0000-0000-000000001070",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001062",+ "id": "00000000-0000-0000-0000-000000001059",},},- "id": "00000000-0000-0000-0000-000000001075",+ "id": "00000000-0000-0000-0000-000000001072","views": undefined,},"agentMessagePart": {"fields": {"createdAt": {- "id": "00000000-0000-0000-0000-000000001077",+ "id": "00000000-0000-0000-0000-000000001074",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001079",+ "id": "00000000-0000-0000-0000-000000001076",},"errorDetails": {- "id": "00000000-0000-0000-0000-000000001091",+ "id": "00000000-0000-0000-0000-000000001088",},"errorMessage": {- "id": "00000000-0000-0000-0000-000000001090",+ "id": "00000000-0000-0000-0000-000000001087",},"fileFilename": {- "id": "00000000-0000-0000-0000-000000001099",+ "id": "00000000-0000-0000-0000-000000001096",},"fileId": {- "id": "00000000-0000-0000-0000-000000001100",+ "id": "00000000-0000-0000-0000-000000001097",},"id": {- "id": "00000000-0000-0000-0000-000000001076",+ "id": "00000000-0000-0000-0000-000000001073",},"message": {- "id": "00000000-0000-0000-0000-000000001102",+ "id": "00000000-0000-0000-0000-000000001099",},"orderIndex": {- "id": "00000000-0000-0000-0000-000000001080",+ "id": "00000000-0000-0000-0000-000000001077",},"providerExecuted": {- "id": "00000000-0000-0000-0000-000000001089",+ "id": "00000000-0000-0000-0000-000000001086",},"providerMetadata": {- "id": "00000000-0000-0000-0000-000000001101",+ "id": "00000000-0000-0000-0000-000000001098",},"reasoningContent": {- "id": "00000000-0000-0000-0000-000000001083",+ "id": "00000000-0000-0000-0000-000000001080",},"sourceDocumentFilename": {- "id": "00000000-0000-0000-0000-000000001098",+ "id": "00000000-0000-0000-0000-000000001095",},"sourceDocumentMediaType": {- "id": "00000000-0000-0000-0000-000000001096",+ "id": "00000000-0000-0000-0000-000000001093",},"sourceDocumentSourceId": {- "id": "00000000-0000-0000-0000-000000001095",+ "id": "00000000-0000-0000-0000-000000001092",},"sourceDocumentTitle": {- "id": "00000000-0000-0000-0000-000000001097",+ "id": "00000000-0000-0000-0000-000000001094",},"sourceUrlSourceId": {- "id": "00000000-0000-0000-0000-000000001092",+ "id": "00000000-0000-0000-0000-000000001089",},"sourceUrlTitle": {- "id": "00000000-0000-0000-0000-000000001094",+ "id": "00000000-0000-0000-0000-000000001091",},"sourceUrlUrl": {- "id": "00000000-0000-0000-0000-000000001093",+ "id": "00000000-0000-0000-0000-000000001090",},"state": {- "id": "00000000-0000-0000-0000-000000001088",+ "id": "00000000-0000-0000-0000-000000001085",},"textContent": {- "id": "00000000-0000-0000-0000-000000001082",+ "id": "00000000-0000-0000-0000-000000001079",},"toolCallId": {- "id": "00000000-0000-0000-0000-000000001085",+ "id": "00000000-0000-0000-0000-000000001082",},"toolInput": {- "id": "00000000-0000-0000-0000-000000001086",+ "id": "00000000-0000-0000-0000-000000001083",},"toolName": {- "id": "00000000-0000-0000-0000-000000001084",+ "id": "00000000-0000-0000-0000-000000001081",},"toolOutput": {- "id": "00000000-0000-0000-0000-000000001087",+ "id": "00000000-0000-0000-0000-000000001084",},"type": {- "id": "00000000-0000-0000-0000-000000001081",+ "id": "00000000-0000-0000-0000-000000001078",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001078",+ "id": "00000000-0000-0000-0000-000000001075",},},- "id": "00000000-0000-0000-0000-000000001103",+ "id": "00000000-0000-0000-0000-000000001100","views": undefined,},"agentTurn": {"fields": {"agentId": {- "id": "00000000-0000-0000-0000-000000001055",+ "id": "00000000-0000-0000-0000-000000001052",},"createdAt": {- "id": "00000000-0000-0000-0000-000000001052",+ "id": "00000000-0000-0000-0000-000000001049",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001054",+ "id": "00000000-0000-0000-0000-000000001051",},"evaluations": {- "id": "00000000-0000-0000-0000-000000001058",+ "id": "00000000-0000-0000-0000-000000001055",},"id": {- "id": "00000000-0000-0000-0000-000000001051",+ "id": "00000000-0000-0000-0000-000000001048",},"messages": {- "id": "00000000-0000-0000-0000-000000001057",+ "id": "00000000-0000-0000-0000-000000001054",},"thread": {- "id": "00000000-0000-0000-0000-000000001056",+ "id": "00000000-0000-0000-0000-000000001053",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001053",+ "id": "00000000-0000-0000-0000-000000001050",},},- "id": "00000000-0000-0000-0000-000000001059",+ "id": "00000000-0000-0000-0000-000000001056","views": undefined,},"agentTurnEvaluation": {"fields": {"comment": {- "id": "00000000-0000-0000-0000-000000001109",+ "id": "00000000-0000-0000-0000-000000001106",},"createdAt": {- "id": "00000000-0000-0000-0000-000000001105",+ "id": "00000000-0000-0000-0000-000000001102",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001107",+ "id": "00000000-0000-0000-0000-000000001104",},"id": {- "id": "00000000-0000-0000-0000-000000001104",+ "id": "00000000-0000-0000-0000-000000001101",},"score": {- "id": "00000000-0000-0000-0000-000000001108",+ "id": "00000000-0000-0000-0000-000000001105",},"turn": {- "id": "00000000-0000-0000-0000-000000001110",+ "id": "00000000-0000-0000-0000-000000001107",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001106",+ "id": "00000000-0000-0000-0000-000000001103",},},- "id": "00000000-0000-0000-0000-000000001111",+ "id": "00000000-0000-0000-0000-000000001108","views": undefined,},"attachment": {@@ -1063,64 +1060,64 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"campaignDelivery": {"fields": {"bouncedAt": {- "id": "00000000-0000-0000-0000-000000001127",+ "id": "00000000-0000-0000-0000-000000001124",},"campaignId": {- "id": "00000000-0000-0000-0000-000000001116",+ "id": "00000000-0000-0000-0000-000000001113",},"claimExpiresAt": {- "id": "00000000-0000-0000-0000-000000001123",+ "id": "00000000-0000-0000-0000-000000001120",},"claimToken": {- "id": "00000000-0000-0000-0000-000000001122",+ "id": "00000000-0000-0000-0000-000000001119",},"complainedAt": {- "id": "00000000-0000-0000-0000-000000001128",+ "id": "00000000-0000-0000-0000-000000001125",},"createdAt": {- "id": "00000000-0000-0000-0000-000000001113",+ "id": "00000000-0000-0000-0000-000000001110",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001115",+ "id": "00000000-0000-0000-0000-000000001112",},"deliveredAt": {- "id": "00000000-0000-0000-0000-000000001126",+ "id": "00000000-0000-0000-0000-000000001123",},"failureReason": {- "id": "00000000-0000-0000-0000-000000001121",+ "id": "00000000-0000-0000-0000-000000001118",},"id": {- "id": "00000000-0000-0000-0000-000000001112",+ "id": "00000000-0000-0000-0000-000000001109",},"personId": {- "id": "00000000-0000-0000-0000-000000001117",+ "id": "00000000-0000-0000-0000-000000001114",},"providerMessageId": {- "id": "00000000-0000-0000-0000-000000001124",+ "id": "00000000-0000-0000-0000-000000001121",},"recipientEmail": {- "id": "00000000-0000-0000-0000-000000001118",+ "id": "00000000-0000-0000-0000-000000001115",},"rejectedAt": {- "id": "00000000-0000-0000-0000-000000001129",+ "id": "00000000-0000-0000-0000-000000001126",},"renderingFailedAt": {- "id": "00000000-0000-0000-0000-000000001130",+ "id": "00000000-0000-0000-0000-000000001127",},"sentAt": {- "id": "00000000-0000-0000-0000-000000001125",+ "id": "00000000-0000-0000-0000-000000001122",},"skipReason": {- "id": "00000000-0000-0000-0000-000000001120",+ "id": "00000000-0000-0000-0000-000000001117",},"state": {- "id": "00000000-0000-0000-0000-000000001119",+ "id": "00000000-0000-0000-0000-000000001116",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001114",+ "id": "00000000-0000-0000-0000-000000001111",},},- "id": "00000000-0000-0000-0000-000000001131",+ "id": "00000000-0000-0000-0000-000000001128","views": undefined,},"company": {@@ -1354,86 +1351,6 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object},},},- "inputAsk": {- "fields": {- "answeredAt": {- "id": "00000000-0000-0000-0000-000000001155",- },- "assignee": {- "id": "00000000-0000-0000-0000-000000001154",- },- "createdAt": {- "id": "00000000-0000-0000-0000-000000001143",- },- "createdBy": {- "id": "00000000-0000-0000-0000-000000001146",- },- "deletedAt": {- "id": "00000000-0000-0000-0000-000000001145",- },- "form": {- "id": "00000000-0000-0000-0000-000000001152",- },- "id": {- "id": "00000000-0000-0000-0000-000000001142",- },- "name": {- "id": "00000000-0000-0000-0000-000000001150",- },- "position": {- "id": "00000000-0000-0000-0000-000000001148",- },- "response": {- "id": "00000000-0000-0000-0000-000000001153",- },- "searchVector": {- "id": "00000000-0000-0000-0000-000000001149",- },- "status": {- "id": "00000000-0000-0000-0000-000000001151",- },- "stepId": {- "id": "00000000-0000-0000-0000-000000001157",- },- "thread": {- "id": "00000000-0000-0000-0000-000000001159",- },- "toolCallId": {- "id": "00000000-0000-0000-0000-000000001158",- },- "updatedAt": {- "id": "00000000-0000-0000-0000-000000001144",- },- "updatedBy": {- "id": "00000000-0000-0000-0000-000000001147",- },- "workflowRun": {- "id": "00000000-0000-0000-0000-000000001156",- },- },- "id": "00000000-0000-0000-0000-000000001165",- "views": {- "allInputAsks": {- "id": "00000000-0000-0000-0000-000000001164",- "viewFieldGroups": {},- "viewFields": {- "assignee": {- "id": "00000000-0000-0000-0000-000000001162",- },- "createdAt": {- "id": "00000000-0000-0000-0000-000000001163",- },- "name": {- "id": "00000000-0000-0000-0000-000000001160",- },- "status": {- "id": "00000000-0000-0000-0000-000000001161",- },- },- "viewGroups": {},- },- },- },"message": {"fields": {"createdAt": {@@ -2157,34 +2074,34 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"messageSuppression": {"fields": {"createdAt": {- "id": "00000000-0000-0000-0000-000000001133",+ "id": "00000000-0000-0000-0000-000000001130",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001135",+ "id": "00000000-0000-0000-0000-000000001132",},"emailAddress": {- "id": "00000000-0000-0000-0000-000000001136",+ "id": "00000000-0000-0000-0000-000000001133",},"id": {- "id": "00000000-0000-0000-0000-000000001132",+ "id": "00000000-0000-0000-0000-000000001129",},"providerEventId": {- "id": "00000000-0000-0000-0000-000000001139",+ "id": "00000000-0000-0000-0000-000000001136",},"reason": {- "id": "00000000-0000-0000-0000-000000001137",+ "id": "00000000-0000-0000-0000-000000001134",},"source": {- "id": "00000000-0000-0000-0000-000000001138",+ "id": "00000000-0000-0000-0000-000000001135",},"unsubscribeTopicId": {- "id": "00000000-0000-0000-0000-000000001140",+ "id": "00000000-0000-0000-0000-000000001137",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001134",+ "id": "00000000-0000-0000-0000-000000001131",},},- "id": "00000000-0000-0000-0000-000000001141",+ "id": "00000000-0000-0000-0000-000000001138","views": undefined,},"messageThread": {@@ -3525,9 +3442,6 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"id": {"id": "00000000-0000-0000-0000-000000000900",},- "inputAsks": {- "id": "00000000-0000-0000-0000-000000000921",- },"name": {"id": "00000000-0000-0000-0000-000000000908",},@@ -3565,70 +3479,70 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"id": "00000000-0000-0000-0000-000000000909",},},- "id": "00000000-0000-0000-0000-000000000941",+ "id": "00000000-0000-0000-0000-000000000940","views": {"allWorkflowRuns": {- "id": "00000000-0000-0000-0000-000000000925",+ "id": "00000000-0000-0000-0000-000000000924","viewFieldGroups": {},"viewFields": {"name": {- "id": "00000000-0000-0000-0000-000000000922",+ "id": "00000000-0000-0000-0000-000000000921",},"status": {- "id": "00000000-0000-0000-0000-000000000924",+ "id": "00000000-0000-0000-0000-000000000923",},"workflow": {- "id": "00000000-0000-0000-0000-000000000923",+ "id": "00000000-0000-0000-0000-000000000922",},},"viewGroups": {},},"workflowRunRecordPageFields": {- "id": "00000000-0000-0000-0000-000000000940",+ "id": "00000000-0000-0000-0000-000000000939","viewFieldGroups": {"general": {- "id": "00000000-0000-0000-0000-000000000938",+ "id": "00000000-0000-0000-0000-000000000937",},"system": {- "id": "00000000-0000-0000-0000-000000000939",+ "id": "00000000-0000-0000-0000-000000000938",},},"viewFields": {"createdAt": {- "id": "00000000-0000-0000-0000-000000000931",+ "id": "00000000-0000-0000-0000-000000000930",},"createdBy": {- "id": "00000000-0000-0000-0000-000000000932",+ "id": "00000000-0000-0000-0000-000000000931",},"endedAt": {- "id": "00000000-0000-0000-0000-000000000930",+ "id": "00000000-0000-0000-0000-000000000929",},"enqueuedAt": {- "id": "00000000-0000-0000-0000-000000000933",+ "id": "00000000-0000-0000-0000-000000000932",},"startedAt": {- "id": "00000000-0000-0000-0000-000000000929",+ "id": "00000000-0000-0000-0000-000000000928",},"state": {- "id": "00000000-0000-0000-0000-000000000934",+ "id": "00000000-0000-0000-0000-000000000933",},"status": {- "id": "00000000-0000-0000-0000-000000000926",+ "id": "00000000-0000-0000-0000-000000000925",},"timelineActivities": {- "id": "00000000-0000-0000-0000-000000000937",+ "id": "00000000-0000-0000-0000-000000000936",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000000935",+ "id": "00000000-0000-0000-0000-000000000934",},"updatedBy": {- "id": "00000000-0000-0000-0000-000000000936",+ "id": "00000000-0000-0000-0000-000000000935",},"workflow": {- "id": "00000000-0000-0000-0000-000000000927",+ "id": "00000000-0000-0000-0000-000000000926",},"workflowVersion": {- "id": "00000000-0000-0000-0000-000000000928",+ "id": "00000000-0000-0000-0000-000000000927",},},"viewGroups": {},@@ -3638,118 +3552,118 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"workflowVersion": {"fields": {"coreWorkflowVersionId": {- "id": "00000000-0000-0000-0000-000000000956",+ "id": "00000000-0000-0000-0000-000000000955",},"createdAt": {- "id": "00000000-0000-0000-0000-000000000943",+ "id": "00000000-0000-0000-0000-000000000942",},"createdBy": {- "id": "00000000-0000-0000-0000-000000000946",+ "id": "00000000-0000-0000-0000-000000000945",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000000945",+ "id": "00000000-0000-0000-0000-000000000944",},"id": {- "id": "00000000-0000-0000-0000-000000000942",+ "id": "00000000-0000-0000-0000-000000000941",},"name": {- "id": "00000000-0000-0000-0000-000000000950",+ "id": "00000000-0000-0000-0000-000000000949",},"position": {- "id": "00000000-0000-0000-0000-000000000948",+ "id": "00000000-0000-0000-0000-000000000947",},"runs": {- "id": "00000000-0000-0000-0000-000000000954",+ "id": "00000000-0000-0000-0000-000000000953",},"searchVector": {- "id": "00000000-0000-0000-0000-000000000949",+ "id": "00000000-0000-0000-0000-000000000948",},"status": {- "id": "00000000-0000-0000-0000-000000000953",+ "id": "00000000-0000-0000-0000-000000000952",},"steps": {- "id": "00000000-0000-0000-0000-000000000955",+ "id": "00000000-0000-0000-0000-000000000954",},"timelineActivities": {- "id": "00000000-0000-0000-0000-000000000957",+ "id": "00000000-0000-0000-0000-000000000956",},"trigger": {- "id": "00000000-0000-0000-0000-000000000952",+ "id": "00000000-0000-0000-0000-000000000951",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000000944",+ "id": "00000000-0000-0000-0000-000000000943",},"updatedBy": {- "id": "00000000-0000-0000-0000-000000000947",+ "id": "00000000-0000-0000-0000-000000000946",},"workflow": {- "id": "00000000-0000-0000-0000-000000000951",+ "id": "00000000-0000-0000-0000-000000000950",},},- "id": "00000000-0000-0000-0000-000000000977",+ "id": "00000000-0000-0000-0000-000000000976","views": {"allWorkflowVersions": {- "id": "00000000-0000-0000-0000-000000000963",+ "id": "00000000-0000-0000-0000-000000000962","viewFieldGroups": {},"viewFields": {"name": {- "id": "00000000-0000-0000-0000-000000000958",+ "id": "00000000-0000-0000-0000-000000000957",},"runs": {- "id": "00000000-0000-0000-0000-000000000962",+ "id": "00000000-0000-0000-0000-000000000961",},"status": {- "id": "00000000-0000-0000-0000-000000000960",+ "id": "00000000-0000-0000-0000-000000000959",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000000961",+ "id": "00000000-0000-0000-0000-000000000960",},"workflow": {- "id": "00000000-0000-0000-0000-000000000959",+ "id": "00000000-0000-0000-0000-000000000958",},},"viewGroups": {},},"workflowVersionRecordPageFields": {- "id": "00000000-0000-0000-0000-000000000976",+ "id": "00000000-0000-0000-0000-000000000975","viewFieldGroups": {"general": {- "id": "00000000-0000-0000-0000-000000000974",+ "id": "00000000-0000-0000-0000-000000000973",},"system": {- "id": "00000000-0000-0000-0000-000000000975",+ "id": "00000000-0000-0000-0000-000000000974",},},"viewFields": {"createdAt": {- "id": "00000000-0000-0000-0000-000000000967",+ "id": "00000000-0000-0000-0000-000000000966",},"createdBy": {- "id": "00000000-0000-0000-0000-000000000969",+ "id": "00000000-0000-0000-0000-000000000968",},"runs": {- "id": "00000000-0000-0000-0000-000000000972",+ "id": "00000000-0000-0000-0000-000000000971",},"status": {- "id": "00000000-0000-0000-0000-000000000964",+ "id": "00000000-0000-0000-0000-000000000963",},"steps": {- "id": "00000000-0000-0000-0000-000000000968",+ "id": "00000000-0000-0000-0000-000000000967",},"timelineActivities": {- "id": "00000000-0000-0000-0000-000000000973",+ "id": "00000000-0000-0000-0000-000000000972",},"trigger": {- "id": "00000000-0000-0000-0000-000000000966",+ "id": "00000000-0000-0000-0000-000000000965",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000000970",+ "id": "00000000-0000-0000-0000-000000000969",},"updatedBy": {- "id": "00000000-0000-0000-0000-000000000971",+ "id": "00000000-0000-0000-0000-000000000970",},"workflow": {- "id": "00000000-0000-0000-0000-000000000965",+ "id": "00000000-0000-0000-0000-000000000964",},},"viewGroups": {},@@ -3759,119 +3673,116 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"workspaceMember": {"fields": {"accountOwnerForCompanies": {- "id": "00000000-0000-0000-0000-000000000997",+ "id": "00000000-0000-0000-0000-000000000996",},"agentChatThreads": {- "id": "00000000-0000-0000-0000-000000001003",+ "id": "00000000-0000-0000-0000-000000001002",},"agentMessages": {- "id": "00000000-0000-0000-0000-000000001002",+ "id": "00000000-0000-0000-0000-000000001001",},"assignedTasks": {- "id": "00000000-0000-0000-0000-000000000995",+ "id": "00000000-0000-0000-0000-000000000994",},"avatarUrl": {- "id": "00000000-0000-0000-0000-000000000991",+ "id": "00000000-0000-0000-0000-000000000990",},"blocklist": {- "id": "00000000-0000-0000-0000-000000000999",+ "id": "00000000-0000-0000-0000-000000000998",},"calendarEventParticipants": {- "id": "00000000-0000-0000-0000-000000001000",+ "id": "00000000-0000-0000-0000-000000000999",},"calendarStartDay": {- "id": "00000000-0000-0000-0000-000000001007",+ "id": "00000000-0000-0000-0000-000000001006",},"colorScheme": {- "id": "00000000-0000-0000-0000-000000000987",+ "id": "00000000-0000-0000-0000-000000000986",},"createdAt": {- "id": "00000000-0000-0000-0000-000000000979",+ "id": "00000000-0000-0000-0000-000000000978",},"createdBy": {- "id": "00000000-0000-0000-0000-000000000982",+ "id": "00000000-0000-0000-0000-000000000981",},"dateFormat": {- "id": "00000000-0000-0000-0000-000000001005",+ "id": "00000000-0000-0000-0000-000000001004",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000000981",+ "id": "00000000-0000-0000-0000-000000000980",},"id": {- "id": "00000000-0000-0000-0000-000000000978",- },- "inputAsks": {- "id": "00000000-0000-0000-0000-000000001009",+ "id": "00000000-0000-0000-0000-000000000977",},"jobTitle": {- "id": "00000000-0000-0000-0000-000000000993",+ "id": "00000000-0000-0000-0000-000000000992",},"locale": {- "id": "00000000-0000-0000-0000-000000000990",+ "id": "00000000-0000-0000-0000-000000000989",},"messageParticipants": {- "id": "00000000-0000-0000-0000-000000000998",+ "id": "00000000-0000-0000-0000-000000000997",},"name": {- "id": "00000000-0000-0000-0000-000000000986",+ "id": "00000000-0000-0000-0000-000000000985",},"numberFormat": {- "id": "00000000-0000-0000-0000-000000001008",+ "id": "00000000-0000-0000-0000-000000001007",},"openRecordIn": {- "id": "00000000-0000-0000-0000-000000000989",+ "id": "00000000-0000-0000-0000-000000000988",},"ownedOpportunities": {- "id": "00000000-0000-0000-0000-000000000996",+ "id": "00000000-0000-0000-0000-000000000995",},"position": {- "id": "00000000-0000-0000-0000-000000000984",+ "id": "00000000-0000-0000-0000-000000000983",},"searchVector": {- "id": "00000000-0000-0000-0000-000000000985",+ "id": "00000000-0000-0000-0000-000000000984",},"timeFormat": {- "id": "00000000-0000-0000-0000-000000001006",+ "id": "00000000-0000-0000-0000-000000001005",},"timeZone": {- "id": "00000000-0000-0000-0000-000000001004",+ "id": "00000000-0000-0000-0000-000000001003",},"timelineActivities": {- "id": "00000000-0000-0000-0000-000000001001",+ "id": "00000000-0000-0000-0000-000000001000",},"uiScale": {- "id": "00000000-0000-0000-0000-000000000988",+ "id": "00000000-0000-0000-0000-000000000987",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000000980",+ "id": "00000000-0000-0000-0000-000000000979",},"updatedBy": {- "id": "00000000-0000-0000-0000-000000000983",+ "id": "00000000-0000-0000-0000-000000000982",},"userEmail": {- "id": "00000000-0000-0000-0000-000000000992",+ "id": "00000000-0000-0000-0000-000000000991",},"userId": {- "id": "00000000-0000-0000-0000-000000000994",+ "id": "00000000-0000-0000-0000-000000000993",},},- "id": "00000000-0000-0000-0000-000000001015",+ "id": "00000000-0000-0000-0000-000000001013","views": {"allWorkspaceMembers": {- "id": "00000000-0000-0000-0000-000000001014",+ "id": "00000000-0000-0000-0000-000000001012","viewFieldGroups": {},"viewFields": {"assignedTasks": {- "id": "00000000-0000-0000-0000-000000001013",+ "id": "00000000-0000-0000-0000-000000001011",},"createdAt": {- "id": "00000000-0000-0000-0000-000000001011",+ "id": "00000000-0000-0000-0000-000000001009",},"name": {- "id": "00000000-0000-0000-0000-000000001010",+ "id": "00000000-0000-0000-0000-000000001008",},"ownedOpportunities": {- "id": "00000000-0000-0000-0000-000000001012",+ "id": "00000000-0000-0000-0000-000000001010",},},"viewGroups": {},diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-field-writability.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-field-writability.spec.tsindex dc1d006c5e6..bc23181b823 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-field-writability.spec.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-field-writability.spec.ts@@ -35,7 +35,7 @@ describe('Standard field writability', () => {).toBe(true);});- it('leaves fields outside protected history, Asks and search vectors OPEN', () => {+ it('leaves fields outside protected history and search vectors OPEN', () => {const nonSearchVectorWritabilities = new Set(standardFlatFieldMetadatas.filter(@@ -48,7 +48,6 @@ describe('Standard field writability', () => {STANDARD_OBJECTS.agentTurn.universalIdentifier,STANDARD_OBJECTS.agentTurnEvaluation.universalIdentifier,STANDARD_OBJECTS.campaignDelivery.universalIdentifier,- STANDARD_OBJECTS.inputAsk.universalIdentifier,STANDARD_OBJECTS.messageSuppression.universalIdentifier,].some((identifier) =>diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.tsindex e5510deca99..51dde9eec60 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts@@ -74,7 +74,6 @@ describe('Standard object readability', () => {STANDARD_OBJECTS.recordShare.universalIdentifier,STANDARD_OBJECTS.workflowRun.universalIdentifier,- STANDARD_OBJECTS.inputAsk.universalIdentifier,STANDARD_OBJECTS.shortLink.universalIdentifier,...inheritedObjectNames.map((objectName) => STANDARD_OBJECTS[objectName].universalIdentifier,@@ -102,27 +101,6 @@ describe('Standard object readability', () => {});});- // A question reads as what asked it does: its run, or for a question asked- // outside a run, its conversation.- it('resolves its run and its conversation as the parents of an inputAsk', () => {- expect(findStandardFlatObjectMetadata('inputAsk')).toMatchObject({- readability: MetadataReadability.INHERITED,- });- expect(- resolveParents('inputAsk').map((parent) =>- parent.kind === 'column'- ? {- joinColumnName: parent.joinColumnName,- parentNameSingular: parent.parentFlatObjectMetadata.nameSingular,- }- : parent.kind,- ),- ).toEqual([- { joinColumnName: 'workflowRunId', parentNameSingular: 'workflowRun' },- { joinColumnName: 'threadId', parentNameSingular: 'agentChatThread' },- ]);- });-it.each(['recordShare', 'shortLink'] as const)('declares %s SYSTEM for readability and writability',(objectName) => {diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-writability.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-writability.spec.tsindex d272b69a790..20dff98c4db 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-writability.spec.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-writability.spec.ts@@ -68,39 +68,4 @@ describe('Standard object writability', () => {);expect([...otherWritabilities]).toEqual([MetadataWritability.OPEN]);});-- it('lets the API write only the assignee of an Ask', () => {- const inputAskObjectMetadata = standardFlatObjectMetadatas.find(- (flatObjectMetadata) => flatObjectMetadata.nameSingular === 'inputAsk',- );-- const writableFieldNames = Object.values(- allFlatEntityMaps.flatFieldMetadataMaps.byUniversalIdentifier,- )- .filter(isDefined)- .filter(- (flatFieldMetadata) =>- flatFieldMetadata.objectMetadataId === inputAskObjectMetadata?.id &&- flatFieldMetadata.writability !== MetadataWritability.SYSTEM,- )- .map((flatFieldMetadata) => flatFieldMetadata.name);-- const gatedFieldNames = [- 'status',- 'response',- 'answeredAt',- 'form',- 'workflowRun',- 'thread',- 'stepId',- 'toolCallId',- ];-- expect(writableFieldNames).toContain('assignee');- expect(- writableFieldNames.filter((fieldName) =>- gatedFieldNames.includes(fieldName),- ),- ).toEqual([]);- });});diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/build-standard-flat-field-metadata-maps.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/build-standard-flat-field-metadata-maps.util.tsindex 6578ebf3ddd..7a5bb731a51 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/build-standard-flat-field-metadata-maps.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/build-standard-flat-field-metadata-maps.util.ts@@ -1,4 +1,3 @@-import { buildInputAskStandardFlatFieldMetadatas } from 'src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-input-ask-standard-flat-field-metadata.util';import { buildCampaignDeliveryStandardFlatFieldMetadatas } from 'src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-campaign-delivery-standard-flat-field-metadata.util';import { buildMessageSuppressionStandardFlatFieldMetadatas } from 'src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-message-suppression-standard-flat-field-metadata.util';import { buildAgentTurnEvaluationStandardFlatFieldMetadatas } from 'src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-turn-evaluation-standard-flat-field-metadata.util';@@ -98,7 +97,6 @@ const STANDARD_FLAT_FIELD_METADATA_BUILDERS_BY_OBJECT_NAME = {workflowRun: buildWorkflowRunStandardFlatFieldMetadatas,workflowVersion: buildWorkflowVersionStandardFlatFieldMetadatas,workspaceMember: buildWorkspaceMemberStandardFlatFieldMetadatas,- inputAsk: buildInputAskStandardFlatFieldMetadatas,} satisfies {[P in AllStandardObjectName]: StandardFieldBuilder<P>;};diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.tsindex deba58b7f80..7183b718dd5 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts@@ -656,33 +656,4 @@ export const buildAgentChatThreadStandardFlatFieldMetadatas = (writability: MetadataWritability.SYSTEM,isAuditLogged: false,},- inputAsks: {- ...createStandardRelationFieldFlatMetadata({- ...args,- context: {- fieldName: 'inputAsks',- type: FieldMetadataType.RELATION,- label: i18nLabel(- msg({ message: 'Asks', context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: 'Questions asked in this conversation',- context: 'fieldMetadata.description',- }),- ),- icon: 'IconHelpCircle',- isUIEditable: false,- isNullable: true,- targetObjectName: 'inputAsk',- targetFieldName: 'thread',- morphId: null,- settings: {- relationType: RelationType.ONE_TO_MANY,- },- },- }),- writability: MetadataWritability.SYSTEM,- isAuditLogged: false,- },});diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-input-ask-standard-flat-field-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-input-ask-standard-flat-field-metadata.util.tsdeleted file mode 100644index 7e234c50e84..00000000000--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-input-ask-standard-flat-field-metadata.util.ts+++ /dev/null@@ -1,565 +0,0 @@-import { msg } from '@lingui/core/macro';-import { i18nLabel } from 'src/engine/workspace-manager/twenty-standard-application/utils/i18n-label.util';-import {- DateDisplayFormat,- FieldMetadataType,- MetadataWritability,- RelationOnDeleteAction,- RelationType,-} from 'twenty-shared/types';--import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';-import { type AllStandardObjectFieldName } from 'src/engine/workspace-manager/twenty-standard-application/types/all-standard-object-field-name.type';-import {- type CreateStandardFieldArgs,- createStandardFieldFlatMetadata,-} from 'src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/create-standard-field-flat-metadata.util';-import { createStandardRelationFieldFlatMetadata } from 'src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/create-standard-relation-field-flat-metadata.util';-import { InputAskStatus } from 'src/modules/input-ask/enums/input-ask-status.enum';--export const buildInputAskStandardFlatFieldMetadatas = ({- now,- objectName,- workspaceId,- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,-}: Omit<- CreateStandardFieldArgs<'inputAsk', FieldMetadataType>,- 'context'->): Record<AllStandardObjectFieldName<'inputAsk'>, FlatFieldMetadata> => ({- id: createStandardFieldFlatMetadata({- objectName,- workspaceId,- context: {- fieldName: 'id',- type: FieldMetadataType.UUID,- label: i18nLabel(msg({ message: `ID`, context: 'fieldMetadata.label' })),- description: i18nLabel(- msg({ message: `ID`, context: 'fieldMetadata.description' }),- ),- icon: 'Icon123',- isSystem: true,- isNullable: false,- isUIEditable: false,- defaultValue: 'uuid',- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- createdAt: createStandardFieldFlatMetadata({- objectName,- workspaceId,- context: {- fieldName: 'createdAt',- type: FieldMetadataType.DATE_TIME,- label: i18nLabel(- msg({ message: `Creation date`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({ message: `Creation date`, context: 'fieldMetadata.description' }),- ),- icon: 'IconCalendar',- isSystem: true,- isNullable: false,- isUIEditable: false,- defaultValue: 'now',- settings: { displayFormat: DateDisplayFormat.RELATIVE },- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- updatedAt: createStandardFieldFlatMetadata({- objectName,- workspaceId,- context: {- fieldName: 'updatedAt',- type: FieldMetadataType.DATE_TIME,- label: i18nLabel(- msg({ message: `Last update`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `Last time the record was changed`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconCalendarClock',- isSystem: true,- isNullable: false,- isUIEditable: false,- defaultValue: 'now',- settings: { displayFormat: DateDisplayFormat.RELATIVE },- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- deletedAt: createStandardFieldFlatMetadata({- objectName,- workspaceId,- context: {- fieldName: 'deletedAt',- type: FieldMetadataType.DATE_TIME,- label: i18nLabel(- msg({ message: `Deleted at`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `Date when the record was deleted`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconCalendarMinus',- isSystem: true,- isNullable: true,- isUIEditable: false,- settings: { displayFormat: DateDisplayFormat.RELATIVE },- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- createdBy: createStandardFieldFlatMetadata({- objectName,- workspaceId,- context: {- fieldName: 'createdBy',- type: FieldMetadataType.ACTOR,- label: i18nLabel(- msg({ message: `Created by`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `The creator of the record`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconCreativeCommonsSa',- isSystem: true,- isUIEditable: false,- isNullable: false,- defaultValue: {- source: "'MANUAL'",- name: "'System'",- workspaceMemberId: null,- },- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- updatedBy: createStandardFieldFlatMetadata({- objectName,- workspaceId,- context: {- fieldName: 'updatedBy',- type: FieldMetadataType.ACTOR,- label: i18nLabel(- msg({ message: `Updated by`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `The workspace member who last updated the record`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconUserCircle',- isSystem: true,- isUIEditable: false,- isNullable: false,- defaultValue: {- source: "'MANUAL'",- name: "'System'",- workspaceMemberId: null,- },- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- position: createStandardFieldFlatMetadata({- objectName,- workspaceId,- context: {- fieldName: 'position',- type: FieldMetadataType.POSITION,- label: i18nLabel(- msg({ message: `Position`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `Ask record position`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconHierarchy2',- isSystem: true,- isNullable: false,- defaultValue: 0,- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- searchVector: createStandardFieldFlatMetadata({- objectName,- workspaceId,- context: {- fieldName: 'searchVector',- type: FieldMetadataType.TS_VECTOR,- label: i18nLabel(- msg({ message: `Search vector`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `Field used for full-text search`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconUser',- isSystem: true,- isNullable: true,- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- name: {- ...createStandardFieldFlatMetadata({- objectName,- workspaceId,- context: {- fieldName: 'name',- type: FieldMetadataType.TEXT,- label: i18nLabel(- msg({ message: `Name`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `What is being asked, in a few words`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconHelpCircle',- isNullable: false,- isUIEditable: false,- defaultValue: "''",- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- writability: MetadataWritability.SYSTEM,- },- status: {- ...createStandardFieldFlatMetadata({- objectName,- workspaceId,- context: {- fieldName: 'status',- type: FieldMetadataType.SELECT,- label: i18nLabel(- msg({ message: `Status`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `Whether this ask is still waiting on someone`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconProgress',- isNullable: false,- isUIEditable: false,- defaultValue: "'PENDING'",- options: [- {- id: 'a1f9a9b6-0e2a-4f0c-9d37-8b4a6b7c1d01',- value: InputAskStatus.PENDING,- label: i18nLabel(- msg({ message: `Pending`, context: 'fieldMetadata.label' }),- ),- position: 0,- color: 'yellow',- },- {- id: 'a1f9a9b6-0e2a-4f0c-9d37-8b4a6b7c1d02',- value: InputAskStatus.ANSWERED,- label: i18nLabel(- msg({ message: `Answered`, context: 'fieldMetadata.label' }),- ),- position: 1,- color: 'green',- },- {- id: 'a1f9a9b6-0e2a-4f0c-9d37-8b4a6b7c1d03',- value: InputAskStatus.CANCELED,- label: i18nLabel(- msg({ message: `Canceled`, context: 'fieldMetadata.label' }),- ),- position: 2,- color: 'gray',- },- ],- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- writability: MetadataWritability.SYSTEM,- },- form: {- ...createStandardFieldFlatMetadata({- objectName,- workspaceId,- context: {- fieldName: 'form',- type: FieldMetadataType.RAW_JSON,- label: i18nLabel(- msg({ message: `Form`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `The questions as they were asked`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconForms',- isNullable: true,- isUIEditable: false,- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- writability: MetadataWritability.SYSTEM,- },- response: {- ...createStandardFieldFlatMetadata({- objectName,- workspaceId,- context: {- fieldName: 'response',- type: FieldMetadataType.RAW_JSON,- label: i18nLabel(- msg({ message: `Response`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `What was answered`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconMessageCheck',- isNullable: true,- isUIEditable: false,- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- writability: MetadataWritability.SYSTEM,- },- answeredAt: {- ...createStandardFieldFlatMetadata({- objectName,- workspaceId,- context: {- fieldName: 'answeredAt',- type: FieldMetadataType.DATE_TIME,- label: i18nLabel(- msg({ message: `Answered at`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `When it was answered`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconCalendarCheck',- isNullable: true,- isUIEditable: false,- settings: { displayFormat: DateDisplayFormat.RELATIVE },- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- writability: MetadataWritability.SYSTEM,- },- stepId: {- ...createStandardFieldFlatMetadata({- objectName,- workspaceId,- context: {- fieldName: 'stepId',- type: FieldMetadataType.UUID,- label: i18nLabel(- msg({ message: `Step ID`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `Which step of the run is waiting`,- context: 'fieldMetadata.description',- }),- ),- icon: 'Icon123',- isSystem: true,- isNullable: true,- isUIEditable: false,- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- writability: MetadataWritability.SYSTEM,- },- toolCallId: {- ...createStandardFieldFlatMetadata({- objectName,- workspaceId,- context: {- fieldName: 'toolCallId',- // Text rather than UUID: a tool call id comes from the model provider- // and is only unique within its conversation, not a uuid we mint.- type: FieldMetadataType.TEXT,- label: i18nLabel(- msg({ message: `Tool call ID`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `Which proposed tool call is waiting`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconTool',- isSystem: true,- isNullable: true,- isUIEditable: false,- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- writability: MetadataWritability.SYSTEM,- },- thread: {- ...createStandardRelationFieldFlatMetadata({- objectName,- workspaceId,- context: {- type: FieldMetadataType.RELATION,- morphId: null,- fieldName: 'thread',- label: i18nLabel(- msg({ message: `Conversation`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `The conversation the question was asked in`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconMessage',- isNullable: true,- isUIEditable: false,- targetObjectName: 'agentChatThread',- targetFieldName: 'inputAsks',- settings: {- relationType: RelationType.MANY_TO_ONE,- onDelete: RelationOnDeleteAction.CASCADE,- joinColumnName: 'threadId',- },- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- writability: MetadataWritability.SYSTEM,- },- assignee: createStandardRelationFieldFlatMetadata({- objectName,- workspaceId,- context: {- type: FieldMetadataType.RELATION,- morphId: null,- fieldName: 'assignee',- label: i18nLabel(- msg({ message: `Assignee`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `Who owes the answer`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconUserCircle',- isNullable: true,- isUIEditable: true,- targetObjectName: 'workspaceMember',- targetFieldName: 'inputAsks',- settings: {- relationType: RelationType.MANY_TO_ONE,- onDelete: RelationOnDeleteAction.SET_NULL,- joinColumnName: 'assigneeId',- },- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- workflowRun: {- ...createStandardRelationFieldFlatMetadata({- objectName,- workspaceId,- context: {- type: FieldMetadataType.RELATION,- morphId: null,- fieldName: 'workflowRun',- label: i18nLabel(- msg({ message: `Workflow Run`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `The run that is waiting`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconSettingsAutomation',- isNullable: true,- isUIEditable: false,- targetObjectName: 'workflowRun',- targetFieldName: 'inputAsks',- settings: {- relationType: RelationType.MANY_TO_ONE,- onDelete: RelationOnDeleteAction.CASCADE,- joinColumnName: 'workflowRunId',- },- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- writability: MetadataWritability.SYSTEM,- },-});diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workflow-run-standard-flat-field-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workflow-run-standard-flat-field-metadata.util.tsindex 2defcbd2d20..7ce07eb0e2c 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workflow-run-standard-flat-field-metadata.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workflow-run-standard-flat-field-metadata.util.ts@@ -662,34 +662,4 @@ export const buildWorkflowRunStandardFlatFieldMetadatas = ({twentyStandardApplicationId,now,}),- inputAsks: createStandardRelationFieldFlatMetadata({- objectName,- workspaceId,- context: {- type: FieldMetadataType.RELATION,- morphId: null,- fieldName: 'inputAsks',- label: i18nLabel(- msg({ message: `Asks`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `What the run is waiting on people for`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconHelpCircle',- isNullable: true,- isUIEditable: false,- targetObjectName: 'inputAsk',- targetFieldName: 'workflowRun',- settings: {- relationType: RelationType.ONE_TO_MANY,- },- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),});diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workspace-member-standard-flat-field-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workspace-member-standard-flat-field-metadata.util.tsindex 4f1ccf01f15..cf43b889e8a 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workspace-member-standard-flat-field-metadata.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workspace-member-standard-flat-field-metadata.util.ts@@ -1001,34 +1001,4 @@ export const buildWorkspaceMemberStandardFlatFieldMetadatas = ({twentyStandardApplicationId,now,}),- inputAsks: createStandardRelationFieldFlatMetadata({- objectName,- workspaceId,- context: {- type: FieldMetadataType.RELATION,- morphId: null,- fieldName: 'inputAsks',- label: i18nLabel(- msg({ message: `Asks`, context: 'fieldMetadata.label' }),- ),- description: i18nLabel(- msg({- message: `What is waiting on this member`,- context: 'fieldMetadata.description',- }),- ),- icon: 'IconHelpCircle',- isNullable: true,- isUIEditable: false,- targetObjectName: 'inputAsk',- targetFieldName: 'assignee',- settings: {- relationType: RelationType.ONE_TO_MANY,- },- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),});diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/build-standard-flat-index-metadata-maps.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/build-standard-flat-index-metadata-maps.util.tsindex f6b9d1412dd..a0ed2119692 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/build-standard-flat-index-metadata-maps.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/build-standard-flat-index-metadata-maps.util.ts@@ -1,4 +1,3 @@-import { buildInputAskStandardFlatIndexMetadatas } from 'src/engine/workspace-manager/twenty-standard-application/utils/index/compute-input-ask-standard-flat-index-metadata.util';import { buildCampaignDeliveryStandardFlatIndexMetadatas } from 'src/engine/workspace-manager/twenty-standard-application/utils/index/compute-campaign-delivery-standard-flat-index-metadata.util';import { buildMessageSuppressionStandardFlatIndexMetadatas } from 'src/engine/workspace-manager/twenty-standard-application/utils/index/compute-message-suppression-standard-flat-index-metadata.util';import { buildAgentTurnEvaluationStandardFlatIndexMetadatas } from 'src/engine/workspace-manager/twenty-standard-application/utils/index/compute-agent-turn-evaluation-standard-flat-index-metadata.util';@@ -92,7 +91,6 @@ const STANDARD_FLAT_INDEX_METADATA_BUILDERS_BY_OBJECT_NAME = {workflowRun: buildWorkflowRunStandardFlatIndexMetadatas,workflowVersion: buildWorkflowVersionStandardFlatIndexMetadatas,workspaceMember: buildWorkspaceMemberStandardFlatIndexMetadatas,- inputAsk: buildInputAskStandardFlatIndexMetadatas,} satisfies {[P in AllStandardObjectName]?: StandardIndexBuilder<P>;};diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-input-ask-standard-flat-index-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-input-ask-standard-flat-index-metadata.util.tsdeleted file mode 100644index 6e97a667335..00000000000--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-input-ask-standard-flat-index-metadata.util.ts+++ /dev/null@@ -1,79 +0,0 @@-import { type FlatIndexMetadata } from 'src/engine/metadata-modules/flat-index-metadata/types/flat-index-metadata.type';-import { type AllStandardObjectIndexName } from 'src/engine/workspace-manager/twenty-standard-application/types/all-standard-object-index-name.type';-import {- type CreateStandardIndexArgs,- createStandardIndexFlatMetadata,-} from 'src/engine/workspace-manager/twenty-standard-application/utils/index/create-standard-index-flat-metadata.util';--export const buildInputAskStandardFlatIndexMetadatas = ({- now,- objectName,- workspaceId,- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,-}: Omit<CreateStandardIndexArgs<'inputAsk'>, 'context'>): Record<- AllStandardObjectIndexName<'inputAsk'>,- FlatIndexMetadata-> => ({- assigneeStatusIndex: createStandardIndexFlatMetadata({- objectName,- workspaceId,- context: {- indexName: 'assigneeStatusIndex',- relatedFieldNames: ['assignee', 'status'],- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- // One Ask per form step of a run, enforced here rather than by the read- // that precedes the insert: a retried or concurrently resumed step would- // otherwise pass that read twice and ask the same question twice. Partial,- // or a soft-deleted row would hold the key against a reopen that cannot see- // it, and an agent's questions, keyed by their tool call, would collide.- workflowRunStepUniqueIndex: createStandardIndexFlatMetadata({- objectName,- workspaceId,- context: {- indexName: 'workflowRunStepUniqueIndex',- relatedFieldNames: ['workflowRun', 'stepId'],- isUnique: true,- indexWhereClause: '"deletedAt" IS NULL AND "toolCallId" IS NULL',- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- // What ending a run reads: every Ask of the run still pending, form or- // agent alike, which the partial unique index above cannot serve.- workflowRunStatusIndex: createStandardIndexFlatMetadata({- objectName,- workspaceId,- context: {- indexName: 'workflowRunStatusIndex',- relatedFieldNames: ['workflowRun', 'status'],- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),- // An agent can ask several times in one conversation, one Ask per call.- threadToolCallUniqueIndex: createStandardIndexFlatMetadata({- objectName,- workspaceId,- context: {- indexName: 'threadToolCallUniqueIndex',- relatedFieldNames: ['thread', 'toolCallId'],- isUnique: true,- indexWhereClause: '"deletedAt" IS NULL AND "toolCallId" IS NOT NULL',- },- standardObjectMetadataRelatedEntityIds,- dependencyFlatEntityMaps,- twentyStandardApplicationId,- now,- }),-});diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.tsindex e2adb00cd86..52684b9ac7e 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts@@ -1753,53 +1753,6 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {twentyStandardApplicationId,now,}),- inputAsk: ({- now,- workspaceId,- standardObjectMetadataRelatedEntityIds,- twentyStandardApplicationId,- dependencyFlatEntityMaps,- }: Omit<CreateStandardObjectArgs<'inputAsk'>, 'context' | 'objectName'>) =>- createStandardObjectFlatMetadata({- objectName: 'inputAsk',- dependencyFlatEntityMaps,- context: {- universalIdentifier: STANDARD_OBJECTS.inputAsk.universalIdentifier,- // The code name is deliberately longer than the label: `ask` alone is- // unsearchable in a codebase, while the label is what anyone reads.- nameSingular: 'inputAsk',- namePlural: 'inputAsks',- labelSingular: i18nLabel(- msg({ message: `Ask`, context: 'objectMetadata.labelSingular' }),- ),- labelPlural: i18nLabel(- msg({ message: `Asks`, context: 'objectMetadata.labelPlural' }),- ),- description: i18nLabel(- msg({- message: `Something waiting on a person before it can continue`,- context: 'objectMetadata.description',- }),- ),- icon: 'IconHelpCircle',- isSystem: true,- isAuditLogged: false,- isUICreatable: false,- isUIEditable: true,- // A question shows what its run or conversation was doing, so it is- // read exactly as they are, never more widely.- readability: MetadataReadability.INHERITED,- readabilityParentFieldMetadataNames: ['workflowRun', 'thread'],- // Only the assignee is written through the API; every other field- // changes with what the Ask gates.- writability: MetadataWritability.OPEN,- labelIdentifierFieldMetadataName: 'name',- },- workspaceId,- standardObjectMetadataRelatedEntityIds,- twentyStandardApplicationId,- now,- }),} satisfies {[P in AllStandardObjectName]: (args: Omit<CreateStandardObjectArgs<P>, 'context' | 'objectName'>,diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view-field/build-standard-flat-view-field-metadata-maps.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view-field/build-standard-flat-view-field-metadata-maps.util.tsindex 4dc26d2aa92..e0e8cf4aee0 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view-field/build-standard-flat-view-field-metadata-maps.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view-field/build-standard-flat-view-field-metadata-maps.util.ts@@ -1,4 +1,3 @@-import { computeStandardInputAskViewFields } from 'src/engine/workspace-manager/twenty-standard-application/utils/view-field/compute-standard-input-ask-view-fields.util';import { createEmptyFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-flat-entity-maps.constant';import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';import { addFlatEntityToFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/add-flat-entity-to-flat-entity-maps-or-throw.util';@@ -70,7 +69,6 @@ const STANDARD_FLAT_VIEW_FIELD_METADATA_BUILDERS_BY_OBJECT_NAME = {workflowRun: computeStandardWorkflowRunViewFields,workflowVersion: computeStandardWorkflowVersionViewFields,workspaceMember: computeStandardWorkspaceMemberViewFields,- inputAsk: computeStandardInputAskViewFields,} as const satisfies {[P in AllStandardObjectName]?: StandardViewFieldBuilder<P>;};diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view-field/compute-standard-input-ask-view-fields.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view-field/compute-standard-input-ask-view-fields.util.tsdeleted file mode 100644index 8531aab024f..00000000000--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view-field/compute-standard-input-ask-view-fields.util.ts+++ /dev/null@@ -1,60 +0,0 @@-import { type FlatViewField } from 'src/engine/metadata-modules/flat-view-field/types/flat-view-field.type';-import {- type CreateStandardViewFieldArgs,- createStandardViewFieldFlatMetadata,-} from 'src/engine/workspace-manager/twenty-standard-application/utils/view-field/create-standard-view-field-flat-metadata.util';--export const computeStandardInputAskViewFields = (- args: Omit<CreateStandardViewFieldArgs<'inputAsk'>, 'context'>,-): Record<string, FlatViewField> => {- return {- allInputAsksName: createStandardViewFieldFlatMetadata({- ...args,- objectName: 'inputAsk',- context: {- viewName: 'allInputAsks',- viewFieldName: 'name',- fieldName: 'name',- position: 0,- isVisible: true,- size: 150,- },- }),- allInputAsksStatus: createStandardViewFieldFlatMetadata({- ...args,- objectName: 'inputAsk',- context: {- viewName: 'allInputAsks',- viewFieldName: 'status',- fieldName: 'status',- position: 1,- isVisible: true,- size: 150,- },- }),- allInputAsksAssignee: createStandardViewFieldFlatMetadata({- ...args,- objectName: 'inputAsk',- context: {- viewName: 'allInputAsks',- viewFieldName: 'assignee',- fieldName: 'assignee',- position: 2,- isVisible: true,- size: 150,- },- }),- allInputAsksCreatedAt: createStandardViewFieldFlatMetadata({- ...args,- objectName: 'inputAsk',- context: {- viewName: 'allInputAsks',- viewFieldName: 'createdAt',- fieldName: 'createdAt',- position: 3,- isVisible: true,- size: 150,- },- }),- };-};diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view/build-standard-flat-view-metadata-maps.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view/build-standard-flat-view-metadata-maps.util.tsindex c501671294a..61154c82802 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view/build-standard-flat-view-metadata-maps.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view/build-standard-flat-view-metadata-maps.util.ts@@ -1,4 +1,3 @@-import { computeStandardInputAskViews } from 'src/engine/workspace-manager/twenty-standard-application/utils/view/compute-standard-input-ask-views.util';import { createEmptyFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-flat-entity-maps.constant';import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';import { addFlatEntityToFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/add-flat-entity-to-flat-entity-maps-or-throw.util';@@ -70,7 +69,6 @@ const STANDARD_FLAT_VIEW_METADATA_BUILDERS_BY_OBJECT_NAME = {workflowRun: computeStandardWorkflowRunViews,workflowVersion: computeStandardWorkflowVersionViews,workspaceMember: computeStandardWorkspaceMemberViews,- inputAsk: computeStandardInputAskViews,} as const satisfies {[P in AllStandardObjectName]?: StandardViewBuilder<P>;};diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view/compute-standard-input-ask-views.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view/compute-standard-input-ask-views.util.tsdeleted file mode 100644index 70274cf9f5e..00000000000--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view/compute-standard-input-ask-views.util.ts+++ /dev/null@@ -1,27 +0,0 @@-import { ViewKey, ViewType } from 'twenty-shared/types';--import { type FlatView } from 'src/engine/metadata-modules/flat-view/types/flat-view.type';-import { INDEX_VIEW_NAME } from 'src/engine/metadata-modules/view/constants/index-view-name.constant';-import {- type CreateStandardViewArgs,- createStandardViewFlatMetadata,-} from 'src/engine/workspace-manager/twenty-standard-application/utils/view/create-standard-view-flat-metadata.util';--export const computeStandardInputAskViews = (- args: Omit<CreateStandardViewArgs<'inputAsk'>, 'context'>,-): Record<string, FlatView> => {- return {- allInputAsks: createStandardViewFlatMetadata({- ...args,- objectName: 'inputAsk',- context: {- viewName: 'allInputAsks',- name: INDEX_VIEW_NAME,- type: ViewType.TABLE,- key: ViewKey.INDEX,- position: 0,- icon: 'IconTable',- },- }),- };-};diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/validate-index-where-clause.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/validate-index-where-clause.util.tsindex 53d1de0a12a..4bf097a7562 100644--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/validate-index-where-clause.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/validate-index-where-clause.util.ts@@ -3,8 +3,6 @@const ALLOWED_INDEX_WHERE_CLAUSES = new Set(['"deletedAt" IS NULL','"isHidden" = true AND "deletedAt" IS NULL',- '"deletedAt" IS NULL AND "toolCallId" IS NULL',- '"deletedAt" IS NULL AND "toolCallId" IS NOT NULL',]);export const validateAndReturnIndexWhereClause = (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.tsdeleted file mode 100644index 1739c6bc74c..00000000000--- a/packages/twenty-server/src/modules/input-ask/answer-ask/dtos/answer-ask-result.dto.ts+++ /dev/null@@ -1,9 +0,0 @@-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/enums/input-ask-status.enum.ts b/packages/twenty-server/src/modules/input-ask/enums/input-ask-status.enum.tsdeleted file mode 100644index 88c2ed2aad8..00000000000--- a/packages/twenty-server/src/modules/input-ask/enums/input-ask-status.enum.ts+++ /dev/null@@ -1,5 +0,0 @@-export enum InputAskStatus {- PENDING = 'PENDING',- ANSWERED = 'ANSWERED',- CANCELED = 'CANCELED',-}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.tsdeleted file mode 100644index da7ecdc221d..00000000000--- a/packages/twenty-server/src/modules/input-ask/filters/input-ask-graphql-api-exception.filter.ts+++ /dev/null@@ -1,11 +0,0 @@-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.tsdeleted file mode 100644index 56777a8ede5..00000000000--- a/packages/twenty-server/src/modules/input-ask/input-ask.exception.ts+++ /dev/null@@ -1,45 +0,0 @@-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/input-ask.module.ts b/packages/twenty-server/src/modules/input-ask/input-ask.module.tsdeleted file mode 100644index 2a1375558b1..00000000000--- a/packages/twenty-server/src/modules/input-ask/input-ask.module.ts+++ /dev/null@@ -1,12 +0,0 @@-import { Module } from '@nestjs/common';--import { RecordPositionModule } from 'src/engine/core-modules/record-position/record-position.module';-import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';-import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';--@Module({- imports: [RecordPositionModule, WorkspaceCacheModule],- providers: [InputAskWorkspaceService],- exports: [InputAskWorkspaceService],-})-export class InputAskModule {}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.tsdeleted file mode 100644index c3e8f54f019..00000000000--- a/packages/twenty-server/src/modules/input-ask/standard-objects/input-ask.workspace-entity.ts+++ /dev/null@@ -1,28 +0,0 @@-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 WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';--export class InputAskWorkspaceEntity extends BaseWorkspaceEntity {- position: number;- name: string;- status: InputAskStatus;- // 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: InputAskForm | null;- response: Record<string, unknown> | null;- answeredAt: string | null;- stepId: string | null;- toolCallId: string | null;- thread: EntityRelation<AgentChatThreadWorkspaceEntity> | null;- threadId: string | null;- assignee: EntityRelation<WorkspaceMemberWorkspaceEntity> | null;- assigneeId: string | null;- workflowRun: EntityRelation<WorkflowRunWorkspaceEntity> | null;- workflowRunId: 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.tsdeleted file mode 100644index 06f9bc56a4c..00000000000--- a/packages/twenty-server/src/modules/input-ask/utils/input-ask-graphql-api-exception-handler.util.ts+++ /dev/null@@ -1,30 +0,0 @@-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.tsdeleted file mode 100644index 2664af3507c..00000000000--- a/packages/twenty-server/src/modules/input-ask/workspace-services/__tests__/input-ask.workspace-service.spec.ts+++ /dev/null@@ -1,240 +0,0 @@-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.tsdeleted file mode 100644index 0b0e50bbea9..00000000000--- a/packages/twenty-server/src/modules/input-ask/workspace-services/input-ask.workspace-service.ts+++ /dev/null@@ -1,331 +0,0 @@-import { Injectable } from '@nestjs/common';--import { STANDARD_OBJECTS } from 'twenty-shared/metadata';-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 { 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';--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 {- constructor(- private readonly workspaceOrmManager: WorkspaceOrmManager,- private readonly recordPositionService: RecordPositionService,- private readonly workspaceCacheService: WorkspaceCacheService,- ) {}-- // 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,- inputAsk,- }: {- workspaceId: string;- inputAsk: InputAskToOpen;- }): Promise<void> {- const key: InputAskKey =- inputAsk.toolCallId !== undefined- ? { threadId: inputAsk.threadId, toolCallId: inputAsk.toolCallId }- : { workflowRunId: inputAsk.workflowRunId, stepId: inputAsk.stepId };-- 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,- });-- try {- await inputAskRepository.insert({- ...inputAsk,- status: InputAskStatus.PENDING,- position,- });-- 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,- },- );- },- });- }-- // 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,- key,- response,- }: {- workspaceId: string;- key: InputAskKey;- response: Record<string, unknown>;- }): 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(),- },- );-- return (result.affected ?? 0) > 0;- },- });- }-- async cancel({- workspaceId,- match,- }: {- workspaceId: string;- 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 },- );-- return (result.affected ?? 0) > 0;- },- });- }-- async findPendingForThread({- workspaceId,- threadId,- }: {- workspaceId: string;- threadId: string;- }): 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 },- }),- });- }-- async hasPendingForThread({- workspaceId,- threadId,- }: {- workspaceId: string;- threadId: string;- }): Promise<boolean> {- return this.execute({- workspaceId,- whenObjectMissing: () => false,- run: (inputAskRepository) =>- inputAskRepository.existsBy({- threadId,- status: InputAskStatus.PENDING,- }),- });- }-- async findPendingForStep({- workspaceId,- workflowRunId,- stepId,- }: {- workspaceId: string;- workflowRunId: string;- 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 },- }),- });- }-- 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,- },- }),- });- }-- private async hasInputAskObject(workspaceId: string): Promise<boolean> {- const { flatObjectMetadataMaps } =- await this.workspaceCacheService.getOrRecompute(workspaceId, [- 'flatObjectMetadataMaps',- ]);-- return isDefined(- flatObjectMetadataMaps.byUniversalIdentifier[- STANDARD_OBJECTS.inputAsk.universalIdentifier- ],- );- }-- // 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> {- 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 () =>- run(- this.workspaceOrmManager.getRepository<InputAskWorkspaceEntity>(- 'inputAsk',- { shouldBypassPermissionChecks: true },- ),- ),- buildSystemAuthContext(workspaceId),- );- }-}diff --git a/packages/twenty-server/src/modules/workflow/common/standard-objects/workflow-run.workspace-entity.ts b/packages/twenty-server/src/modules/workflow/common/standard-objects/workflow-run.workspace-entity.tsindex 32875ea62c3..2784b9f1b11 100644--- a/packages/twenty-server/src/modules/workflow/common/standard-objects/workflow-run.workspace-entity.ts+++ b/packages/twenty-server/src/modules/workflow/common/standard-objects/workflow-run.workspace-entity.ts@@ -1,4 +1,3 @@-import { type InputAskWorkspaceEntity } from 'src/modules/input-ask/standard-objects/input-ask.workspace-entity';import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';import { registerEnumType } from '@nestjs/graphql';@@ -74,6 +73,5 @@ export class WorkflowRunWorkspaceEntity extends BaseWorkspaceEntity {coreWorkflowId: string | null;coreWorkflowVersionId: string | null;agentChatThreads: EntityRelation<AgentChatThreadWorkspaceEntity[]>;- inputAsks: EntityRelation<InputAskWorkspaceEntity[]>;timelineActivities: EntityRelation<TimelineActivityWorkspaceEntity[]>;}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.tsindex 33f0badc293..7ac2b760639 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,11 +1,8 @@-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.tsdeleted file mode 100644index 951e6a34a1c..00000000000--- a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-pending-ask.type.ts+++ /dev/null@@ -1,7 +0,0 @@-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.tsindex 30483c0ae15..db57d8daaf3 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@@ -3,8 +3,9 @@ import { Injectable, Logger } from '@nestjs/common';import {ASK_QUESTIONS_TOOL_NAME,PROPOSE_EMAIL_TOOL_NAME,+ REQUEST_FORM_TOOL_NAME,} from 'twenty-shared/ai';-import { isDefined, isNonEmptyArray, resolveInput } from 'twenty-shared/utils';+import { isDefined, 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';@@ -14,6 +15,7 @@ import { AgentAsyncExecutorService } from 'src/engine/metadata-modules/ai/ai-ageimport { 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 { createRequestFormTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/request-form.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';@@ -155,6 +157,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {isWorkspaceSetupThread: false,}),[PROPOSE_EMAIL_TOOL_NAME]: createProposeEmailTool(),+ [REQUEST_FORM_TOOL_NAME]: createRequestFormTool(),}: {},actorContext: executionContext.isActingOnBehalfOfUser@@ -194,16 +197,13 @@ 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 (!isNonEmptyArray(recordedConversation?.pendingAsks)) {+ if (recordedConversation?.isAwaitingAnswer !== true) {return {error: 'Agent asked a question that could not be recorded.',};}- return {- pendingEvent: true,- pendingAsks: recordedConversation.pendingAsks,- };+ return { pendingEvent: true };}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.tsindex 31a4682349a..bfd30030d68 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. 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.`;+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. When you need typed values instead, such as a date, an amount or a record to pick, call request_form. 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.tsindex f968b310c40..9d0bca9a478 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@@ -6,6 +6,8 @@ import { convertToModelMessages, type ModelMessage } from 'ai';import {type ExtendedUIMessage,type ExtendedUIMessagePart,+ REQUEST_FORM_TOOL_NAME,+ type RequestFormToolInput,} from 'twenty-shared/ai';import { isDefined } from 'twenty-shared/utils';import { type QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';@@ -20,17 +22,12 @@ import { finalizeDanglingToolParts } from 'src/engine/metadata-modules/ai/ai-ageimport { 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 { 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 { buildRequestFormPendingOutput } from 'src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool';import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';import { 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 {- 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';export type RecordedExecutionResult = {@@ -38,22 +35,16 @@ export type RecordedExecutionResult = {isPaused?: boolean;};-export type AnsweredToolPart = {- id: string;- messageId: string;- turnId: string | null;-};-export type RecordedConversation = {threadId: string;- pendingAsks: WorkflowPendingAsk[];+ isAwaitingAnswer: boolean;};-// A conversation is recorded only for an execution of an agent step that asks-// a question, and continued when that execution resumes. Each gets its own, so-// a loop iteration or a retry never reads or continues another one's messages.-// The conversation has no owner: it belongs to the run and is readable by-// whoever can read the run.+// A conversation is recorded only for an execution of a step that waits on a+// person, a form or an agent that asks, and continued when that execution+// resumes. Each gets its own, so a loop iteration or a retry never reads or+// continues another one's messages. The conversation has no owner: it belongs+// to the run and is readable by whoever can read the run.@Injectable()export class WorkflowAgentConversationWorkspaceService {constructor(@@ -88,22 +79,19 @@ export class WorkflowAgentConversationWorkspaceService {initiatorUserWorkspaceId: string | null;executionResult: RecordedExecutionResult;}): Promise<RecordedConversation | null> {- const { flatFieldMetadataMaps } =- await this.workspaceCacheService.getOrRecompute(workspaceId, [- 'flatFieldMetadataMaps',- ]);+ const conversation = await this.openConversation({+ workspaceId,+ workflowRunId,+ stepId,+ title,+ agentId,+ });- if (!hasWorkflowRunThreadFields(flatFieldMetadataMaps)) {+ if (!isDefined(conversation)) {return null;}- const threadInsertResult = await this.threadRepository.insert(workspaceId, {- title,- workflowRunId,- });- const threadId = threadInsertResult.identifiers[0].id as string;-- const turnId = await this.insertTurn({ workspaceId, threadId, agentId });+ const { threadId, turnId } = conversation;await this.insertMessage({workspaceId,@@ -115,22 +103,69 @@ export class WorkflowAgentConversationWorkspaceService {parts: [{ type: 'text', text: prompt }],});- await this.workflowRunWorkspaceService.setStepThreadId({- stepId,+ const isAwaitingAnswer = await this.recordReply({+ workspaceId,threadId,- workflowRunId,+ turnId,+ agentId,+ executionResult,+ });++ return { threadId, isAwaitingAnswer };+ }++ // A form step asks for its fields the way an agent would, so it is answered+ // like any call that waits on a person. The call is named after the step.+ async recordFormRequest({+ workspaceId,+ workflowRunId,+ stepId,+ title,+ fields,+ }: {+ workspaceId: string;+ workflowRunId: string;+ stepId: string;+ title: string;+ fields: RequestFormToolInput['fields'];+ }): Promise<void> {+ const conversation = await this.openConversation({workspaceId,+ workflowRunId,+ stepId,+ title,+ agentId: null,});- const pendingAsks = await this.recordReply({+ if (!isDefined(conversation)) {+ return;+ }++ const { threadId, turnId } = conversation;++ const messageId = await this.insertMessage({workspaceId,threadId,turnId,- agentId,- executionResult,+ role: AgentMessageRole.ASSISTANT,+ agentId: null,+ senderUserWorkspaceId: null,+ parts: [+ {+ type: `tool-${REQUEST_FORM_TOOL_NAME}`,+ toolCallId: stepId,+ state: 'output-available',+ input: { fields },+ output: buildRequestFormPendingOutput(),+ } as ExtendedUIMessagePart,+ ],});- return { threadId, pendingAsks };+ await this.threadRepository.update(+ workspaceId,+ { id: threadId },+ { pendingQuestionMessageId: messageId },+ );}// Continues a conversation whose question has been answered: the answer is@@ -148,7 +183,7 @@ export class WorkflowAgentConversationWorkspaceService {}): Promise<RecordedConversation> {const turnId = await this.insertTurn({ workspaceId, threadId, agentId });- const pendingAsks = await this.recordReply({+ const isAwaitingAnswer = await this.recordReply({workspaceId,threadId,turnId,@@ -156,7 +191,7 @@ export class WorkflowAgentConversationWorkspaceService {executionResult,});- return { threadId, pendingAsks };+ return { threadId, isAwaitingAnswer };}async loadModelMessages({@@ -186,66 +221,9 @@ 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.+ // A paused reply marks its conversation as waiting on its calls, all of+ // which have to be answerable: one call nobody can answer would keep the+ // step waiting forever on the others, so the step fails instead.private async recordReply({workspaceId,threadId,@@ -258,14 +236,14 @@ export class WorkflowAgentConversationWorkspaceService {turnId: string;agentId: string | null;executionResult: RecordedExecutionResult;- }): Promise<WorkflowPendingAsk[]> {+ }): Promise<boolean> {const replyParts = mapAiStepsToUiMessageParts(executionResult.steps ?? []);if (replyParts.length === 0) {- return [];+ return false;}- await this.insertMessage({+ const messageId = await this.insertMessage({workspaceId,threadId,turnId,@@ -275,25 +253,64 @@ export class WorkflowAgentConversationWorkspaceService {parts: replyParts,});- if (executionResult.isPaused !== true) {- return [];+ const awaitingParts = findAwaitingPausingToolParts(replyParts);++ if (+ executionResult.isPaused !== true ||+ awaitingParts.length === 0 ||+ !awaitingParts.every(({ isAnswerable }) => isAnswerable)+ ) {+ return false;}- const pendingAsks: WorkflowPendingAsk[] = [];+ await this.threadRepository.update(+ workspaceId,+ { id: threadId },+ { pendingQuestionMessageId: messageId },+ );++ return true;+ }- 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 [];- }+ // Only a workspace whose conversations can name a run records one.+ private async openConversation({+ workspaceId,+ workflowRunId,+ stepId,+ title,+ agentId,+ }: {+ workspaceId: string;+ workflowRunId: string;+ stepId: string;+ title: string;+ agentId: string | null;+ }): Promise<{ threadId: string; turnId: string } | null> {+ const { flatFieldMetadataMaps } =+ await this.workspaceCacheService.getOrRecompute(workspaceId, [+ 'flatFieldMetadataMaps',+ ]);- pendingAsks.push({ ...ask, threadId, toolCallId });+ if (!hasWorkflowRunThreadFields(flatFieldMetadataMaps)) {+ return null;}- return pendingAsks;+ const threadInsertResult = await this.threadRepository.insert(workspaceId, {+ title,+ workflowRunId,+ });+ const threadId = threadInsertResult.identifiers[0].id as string;++ const turnId = await this.insertTurn({ workspaceId, threadId, agentId });++ await this.workflowRunWorkspaceService.setStepThreadId({+ stepId,+ threadId,+ workflowRunId,+ workspaceId,+ });++ return { threadId, turnId };}private async insertTurn({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.tsindex 1600d235b9c..6a250bcc57e 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,8 +1,10 @@import { Module } from '@nestjs/common';+import { WorkflowAgentConversationModule } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module';import { FormWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/form/form.workflow-action';@Module({+ imports: [WorkflowAgentConversationModule],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.tsindex ca94c076509..e38bb19126d 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@@ -9,13 +9,19 @@ import {import { type WorkflowActionInput } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';import { type WorkflowActionOutput } from 'src/modules/workflow/workflow-executor/types/workflow-action-output.type';import { findStepOrThrow } from 'src/modules/workflow/workflow-executor/utils/find-step-or-throw.util';+import { 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';@Injectable()export class FormWorkflowAction implements WorkflowAction {+ constructor(+ private readonly workflowAgentConversationService: WorkflowAgentConversationWorkspaceService,+ ) {}+async execute({currentStepId,steps,+ runInfo,}: WorkflowActionInput): Promise<WorkflowActionOutput> {const step = findStepOrThrow({stepId: currentStepId,@@ -29,14 +35,16 @@ export class FormWorkflowAction implements WorkflowAction {);}- return {- pendingEvent: true,- pendingAsks: [- {- name: step.name,- form: { kind: 'formFields', fields: step.settings.input },- },- ],- };+ // A workspace 2.44 has not reached yet cannot record the conversation, and+ // its upgrade records one for every form still waiting.+ await this.workflowAgentConversationService.recordFormRequest({+ workspaceId: runInfo.workspaceId,+ workflowRunId: runInfo.workflowRunId,+ stepId: currentStepId,+ title: step.name,+ fields: step.settings.input,+ });++ return { pendingEvent: true };}}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.tsindex 88b559af1dd..681594c8ea9 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,7 +502,6 @@ 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.tsdeleted file mode 100644index e3da8efb7d7..00000000000--- a/packages/twenty-server/src/modules/workflow/workflow-runner/utils/__tests__/can-workflow-run-have-asks.util.spec.ts+++ /dev/null@@ -1,54 +0,0 @@-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.tsdeleted file mode 100644index 4aabf961a5e..00000000000--- a/packages/twenty-server/src/modules/workflow/workflow-runner/utils/can-workflow-run-have-asks.util.ts+++ /dev/null@@ -1,17 +0,0 @@-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.tsdeleted file mode 100644index 8e0e2bfdb5e..00000000000--- a/packages/twenty-server/src/modules/workflow/workflow-runner/utils/get-run-initiator-workspace-member-id.util.ts+++ /dev/null@@ -1,12 +0,0 @@-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.conversation.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.tsnew file mode 100644index 00000000000..60ef10b5b8b--- /dev/null+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.conversation.spec.ts@@ -0,0 +1,236 @@+import { StepStatus } from 'twenty-shared/workflow';+import { IsNull } from 'typeorm';++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 = [+ {+ header: 'Plan',+ question: 'Which plan?',+ options: [{ label: 'Pro' }, { label: 'Team' }],+ },+];++describe('WorkflowRunWorkspaceService conversations', () => {+ const buildService = ({+ status = WorkflowRunStatus.RUNNING,+ stepInfo = {+ status: StepStatus.PENDING,+ threadId: 'thread-id',+ } as Record<string, unknown>,+ } = {}) => {+ const threadRepository = {+ find: jest+ .fn()+ .mockResolvedValue([+ { id: 'thread-id', pendingQuestionMessageId: 'message-id' },+ ]),+ update: jest.fn().mockResolvedValue({ affected: 1 }),+ };+ const messagePartRepository = {+ find: jest.fn().mockResolvedValue([+ {+ id: 'part-id',+ toolName: 'ask_questions',+ toolInput: { questions: QUESTIONS },+ toolOutput: { result: { questions: QUESTIONS, status: 'pending' } },+ },+ ]),+ update: jest.fn().mockResolvedValue({ affected: 1 }),+ };+ const service = new WorkflowRunWorkspaceService(+ {} as never,+ {} as never,+ { incrementCounterForEvent: jest.fn() } as never,+ {} as never,+ threadRepository as never,+ messagePartRepository as never,+ );++ // The run lock serializes these methods with every other step write.+ Object.assign(service, {+ cacheLockService: {+ withLock: jest.fn().mockImplementation((work) => work()),+ },+ });++ const step = { id: 'step-id', name: 'Ask' };+ const workflowRun = {+ id: 'workflow-run-id',+ status,+ state: { flow: { steps: [step] }, stepInfos: { 'step-id': stepInfo } },+ };++ jest+ .spyOn(service, 'getWorkflowRunOrFail')+ .mockResolvedValue(workflowRun as never);++ const updateWorkflowRun = jest+ .spyOn(service, 'updateWorkflowRun')+ .mockResolvedValue(undefined);++ return {+ service,+ step,+ threadRepository,+ messagePartRepository,+ updateWorkflowRun,+ };+ };++ describe('findStepAwaitingAnswer', () => {+ const findStep = (service: WorkflowRunWorkspaceService) =>+ service.findStepAwaitingAnswer({+ threadId: 'thread-id',+ workflowRunId: 'workflow-run-id',+ workspaceId: 'workspace-id',+ });++ it('finds the PENDING step whose current execution holds the conversation', async () => {+ const { service, step } = buildService();++ expect(await findStep(service)).toEqual(step);+ });++ it.each([+ ['the run is no longer running', { status: WorkflowRunStatus.STOPPED }],+ [+ 'the step already resumed',+ { stepInfo: { status: StepStatus.RUNNING, threadId: 'thread-id' } },+ ],+ [+ 'a retry or a loop iteration replaced the conversation',+ { stepInfo: { status: StepStatus.PENDING, threadId: 'other-thread' } },+ ],+ [+ 'the step failed while waiting',+ {+ stepInfo: {+ status: StepStatus.PENDING,+ threadId: 'thread-id',+ error: 'boom',+ },+ },+ ],+ ])('finds nothing when %s', async (_description, overrides) => {+ const { service } = buildService(overrides);++ expect(await findStep(service)).toBeNull();+ });+ });++ 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 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', () => {+ const endRun = (service: WorkflowRunWorkspaceService) =>+ service.endWorkflowRun({+ workflowRunId: 'workflow-run-id',+ workspaceId: 'workspace-id',+ status: WorkflowRunStatus.STOPPED,+ });++ it('stops its conversations waiting and closes their calls as skipped', async () => {+ const { service, threadRepository, messagePartRepository } =+ buildService();++ await endRun(service);++ expect(threadRepository.update).toHaveBeenCalledWith(+ 'workspace-id',+ {+ id: 'thread-id',+ pendingQuestionMessageId: 'message-id',+ activeStreamId: IsNull(),+ },+ { pendingQuestionMessageId: null },+ );+ expect(messagePartRepository.update).toHaveBeenCalledWith(+ 'workspace-id',+ { id: 'part-id' },+ {+ toolOutput: expect.objectContaining({+ result: { questions: QUESTIONS, status: 'skipped' },+ }),+ },+ );+ });++ it('leaves a conversation to the answer holding its claim', async () => {+ const { service, threadRepository, messagePartRepository } =+ buildService();++ threadRepository.update.mockResolvedValue({ affected: 0 });++ await endRun(service);++ expect(messagePartRepository.update).not.toHaveBeenCalled();+ });++ it('still ends the run when its conversations cannot be closed', async () => {+ const { service, threadRepository, updateWorkflowRun } = buildService();++ threadRepository.find.mockRejectedValue(new Error('db down'));++ await endRun(service);++ expect(updateWorkflowRun).toHaveBeenCalled();+ });++ it('leaves conversations alone for a run that never had one', async () => {+ const { service, threadRepository } = buildService({+ stepInfo: { status: StepStatus.SUCCESS },+ });++ await endRun(service);++ expect(threadRepository.find).not.toHaveBeenCalled();+ });+ });+});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.tsdeleted file mode 100644index 23fc019a3aa..00000000000--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.input-ask.spec.ts+++ /dev/null@@ -1,366 +0,0 @@-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/workflow-run.module.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.tsindex 94daa817e8f..aa9827b44c5 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@@ -5,8 +5,8 @@ import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.mimport { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';import { RecordPositionModule } from 'src/engine/core-modules/record-position/record-position.module';+import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';import { WorkflowRunRecordShareModule } from 'src/engine/core-modules/workflow/workflow-run-record-share.module';-import { InputAskModule } from 'src/modules/input-ask/input-ask.module';import { WorkflowCommonModule } from 'src/modules/workflow/common/workflow-common.module';import { DeleteWorkflowRunsCommand } from 'src/modules/workflow/workflow-runner/workflow-run/command/delete-workflow-runs.command';import { WorkflowRunStepLogWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service';@@ -21,7 +21,7 @@ import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runneWorkspaceIteratorModule,FeatureFlagModule,WorkflowRunRecordShareModule,- InputAskModule,+ AgentHistoryModule,],providers: [WorkflowRunWorkspaceService,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.tsindex 163163a4be7..4a7ce641a0a 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@@ -3,6 +3,7 @@ import { Injectable, Logger } from '@nestjs/common';import { type ActorMetadata } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';import { StepStatus, type WorkflowRunStepInfo } from 'twenty-shared/workflow';+import { IsNull, Not } from 'typeorm';import { v4 } from 'uuid';import { WithLock } from 'src/engine/core-modules/cache-lock/with-lock.decorator';@@ -12,7 +13,11 @@ import { RecordPositionService } from 'src/engine/core-modules/record-position/simport { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';-import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';+import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';+import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';+import { 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 { skipAwaitingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/skip-awaiting-tool-parts.util';import {WorkflowRunStatus,type WorkflowRunState,@@ -21,19 +26,12 @@ 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 StepInputResolution =- | { status: 'RESOLVED'; stepId: string }- | { status: 'NOT_AWAITING' };@Injectable()export class WorkflowRunWorkspaceService {@@ -43,8 +41,11 @@ export class WorkflowRunWorkspaceService {private readonly workspaceOrmManager: WorkspaceOrmManager,private readonly recordPositionService: RecordPositionService,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<AgentMessagePartWorkspaceEntity>,) {}async createCoreWorkflowRun({@@ -206,18 +207,22 @@ export class WorkflowRunWorkspaceService {await this.updateWorkflowRun({ workflowRunId, workspaceId, partialUpdate });- // A run that ends can no longer consume an answer, so an Ask still- // 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)}`,- );- });+ // A run that ends can no longer consume an answer, so the calls its+ // conversations wait on are closed. This is housekeeping: the run is over+ // either way, and a failure here only leaves a call that looks waiting.+ if (+ Object.values(workflowRunToUpdate.state?.stepInfos ?? {}).some(+ (stepInfo) => isDefined(stepInfo?.threadId),+ )+ ) {+ await this.closeWaitingConversations({+ workflowRunId,+ workspaceId,+ }).catch((error: unknown) => {+ this.logger.error(+ `Failed to close the conversations of workflow run ${workflowRunId} in workspace ${workspaceId}: ${error instanceof Error ? error.message : String(error)}`,+ );+ });}const metricKey =@@ -241,20 +246,15 @@ 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;}) {@@ -263,20 +263,6 @@ 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,@@ -444,14 +430,12 @@ 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;@@ -472,19 +456,6 @@ 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,@@ -502,35 +473,24 @@ export class WorkflowRunWorkspaceService {return true;}- // 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 resolveStepAwaitingToolCall({+ // A run conversation names no step: it belongs to the step whose current+ // execution recorded it, so one replaced by a retry or a later loop+ // iteration belongs to no step anymore.+ async findStepAwaitingAnswer({threadId,- toolCallId,- response,workflowRunId,workspaceId,}: {threadId: string;- toolCallId: string;- response: Record<string, unknown>;workflowRunId: string;workspaceId: string;- }): Promise<StepInputResolution> {+ }): Promise<WorkflowAction | null> {const workflowRun = await this.getWorkflowRunOrFail({workflowRunId,workspaceId,});- // A run conversation names no step: it belongs to the step whose current- // execution recorded it, so one replaced by a retry or a later loop- // iteration belongs to no step anymore.- const [stepId, currentStepInfo] =+ const [stepId, stepInfo] =Object.entries(workflowRun.state?.stepInfos ?? {}).find(([, stepInfo]) => stepInfo?.threadId === threadId,) ?? [];@@ -538,24 +498,15 @@ export class WorkflowRunWorkspaceService {if (workflowRun.status !== WorkflowRunStatus.RUNNING ||!isDefined(stepId) ||- !isDefined(currentStepInfo) ||- isDefined(currentStepInfo.error) ||- currentStepInfo.status !== StepStatus.PENDING+ isDefined(stepInfo?.error) ||+ stepInfo?.status !== StepStatus.PENDING) {- return { status: 'NOT_AWAITING' };- }-- const hasAnswered = await this.inputAskWorkspaceService.answer({- workspaceId,- key: { threadId, toolCallId },- response,- });-- if (!hasAnswered) {- return { status: 'NOT_AWAITING' };+ return null;}- return { status: 'RESOLVED', stepId };+ return (+ workflowRun.state?.flow?.steps?.find((step) => step.id === stepId) ?? null+ );}@WithLock('workflowRunId')@@ -715,6 +666,47 @@ export class WorkflowRunWorkspaceService {}, authContext);}+ private async closeWaitingConversations({+ workflowRunId,+ workspaceId,+ }: {+ workflowRunId: string;+ workspaceId: string;+ }): Promise<void> {+ // An answer holding a conversation's claim decides its calls: it closes+ // them itself once it finds the run over.+ const waitingThreads = await this.threadRepository.find(workspaceId, {+ where: {+ workflowRunId,+ pendingQuestionMessageId: Not(IsNull()),+ activeStreamId: IsNull(),+ },+ select: ['id', 'pendingQuestionMessageId'],+ });++ for (const { id, pendingQuestionMessageId } of waitingThreads) {+ if (!isDefined(pendingQuestionMessageId)) {+ continue;+ }++ const { affected } = await this.threadRepository.update(+ workspaceId,+ { id, pendingQuestionMessageId, activeStreamId: IsNull() },+ { pendingQuestionMessageId: null },+ );++ if (affected === 0) {+ continue;+ }++ await skipAwaitingToolParts({+ messagePartRepository: this.messagePartRepository,+ messageId: pendingQuestionMessageId,+ workspaceId,+ });+ }+ }+private getInitState(workflowVersion: Pick<WorkflowVersionWorkspaceEntity, 'trigger' | 'steps'>,triggerPayload: object,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.tsindex c4700ad36d0..1a80e5b9aa9 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@@ -6,7 +6,6 @@ import { WorkflowCommonModule } from 'src/modules/workflow/common/workflow-commoimport { 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 +26,6 @@ import { WorkflowVersionCoreModule } from 'src/engine/core-modules/workflow/workCodeStepBuildModule,WorkflowCoreModule,WorkflowVersionCoreModule,- 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.tsindex ba4e03a4eb1..1e7eb0d0931 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,9 @@+import { WorkflowActionType } from 'twenty-shared/workflow';+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 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 { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';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,58 +13,58 @@ import { WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-ruconst 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',-};++const AGENT_STEP = {+ id: 'agent-step-id',+ type: WorkflowActionType.AI_AGENT,+} as WorkflowAction;++const FORM_STEP = {+ id: 'form-step-id',+ type: WorkflowActionType.FORM,+ settings: { input: [] },+} as unknown as WorkflowAction;describe('WorkflowRunnerWorkspaceService', () => {const messageQueueService = { add: jest.fn() };- const workflowAgentConversationWorkspaceService = {- recordAnswer: jest.fn().mockResolvedValue({ hasAwaitingToolCalls: false }),+ const workflowRunWorkspaceService = {+ updateStepInfoIfPending: jest.fn().mockResolvedValue(true),+ };+ const workflowVersionStepOperationsWorkspaceService = {+ enrichFormStepResponse: jest+ .fn()+ .mockImplementation(async ({ response }) => ({+ ...response,+ enriched: true,+ })),};const service = new WorkflowRunnerWorkspaceService(- {} as WorkflowRunWorkspaceService,+ workflowRunWorkspaceService as unknown as WorkflowRunWorkspaceService,messageQueueService as unknown as MessageQueueService,- {} as WorkflowVersionStepOperationsWorkspaceService,+ workflowVersionStepOperationsWorkspaceService as unknown as WorkflowVersionStepOperationsWorkspaceService,{} as WorkflowThrottlingWorkspaceService,{} as CoreWorkflowRunnerService,{} as WorkflowVersionCoreSyncService,- workflowAgentConversationWorkspaceService as unknown as WorkflowAgentConversationWorkspaceService,);- const resumeAnsweredAgentStep = () =>- service.resumeAnsweredAgentStep({+ const resumeAnsweredStep = (step: WorkflowAction) =>+ service.resumeAnsweredStep({workspaceId: WORKSPACE_ID,workflowRunId: WORKFLOW_RUN_ID,- stepId: 'agent-step-id',+ step,threadId: THREAD_ID,- toolPart: TOOL_PART,- toolResult: { success: true },- answerText: 'Send it',- senderUserWorkspaceId: 'user-workspace-id',+ response: { discount: 15 },});beforeEach(() => {jest.clearAllMocks();});- describe('resumeAnsweredAgentStep', () => {- it('records the answer, then schedules an explicit resume of the step in its conversation', async () => {- await resumeAnsweredAgentStep();+ describe('resumeAnsweredStep', () => {+ it('schedules an explicit resume of an agent step in its conversation', async () => {+ await resumeAnsweredStep(AGENT_STEP);- 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,{@@ -73,29 +75,43 @@ describe('WorkflowRunnerWorkspaceService', () => {expect.objectContaining({ id: WORKFLOW_RUN_ID }),);expect(- workflowAgentConversationWorkspaceService.recordAnswer.mock- .invocationCallOrder[0],- ).toBeLessThan(messageQueueService.add.mock.invocationCallOrder[0]);+ workflowRunWorkspaceService.updateStepInfoIfPending,+ ).not.toHaveBeenCalled();});- it('schedules nothing while another call of the step still waits on its answer', async () => {- workflowAgentConversationWorkspaceService.recordAnswer.mockResolvedValueOnce(- { hasAwaitingToolCalls: true },- );-- await resumeAnsweredAgentStep();+ it('completes a form step with its enriched answer, then resumes the run after it', async () => {+ await resumeAnsweredStep(FORM_STEP);- expect(messageQueueService.add).not.toHaveBeenCalled();+ expect(+ workflowRunWorkspaceService.updateStepInfoIfPending,+ ).toHaveBeenCalledWith({+ stepId: 'form-step-id',+ stepInfo: {+ status: 'SUCCESS',+ result: { discount: 15, enriched: true },+ },+ expectedThreadId: THREAD_ID,+ workspaceId: WORKSPACE_ID,+ workflowRunId: WORKFLOW_RUN_ID,+ });+ expect(messageQueueService.add).toHaveBeenCalledWith(+ RUN_WORKFLOW_JOB_NAME,+ {+ workspaceId: WORKSPACE_ID,+ workflowRunId: WORKFLOW_RUN_ID,+ lastExecutedStepId: 'form-step-id',+ },+ expect.objectContaining({ id: WORKFLOW_RUN_ID }),+ );});- it('schedules nothing when the answer cannot be recorded', async () => {- workflowAgentConversationWorkspaceService.recordAnswer.mockRejectedValueOnce(- new Error('History unavailable'),+ it('resumes nothing when the form step no longer waits on this conversation', async () => {+ workflowRunWorkspaceService.updateStepInfoIfPending.mockResolvedValueOnce(+ false,);- await expect(resumeAnsweredAgentStep()).rejects.toThrow(- 'History unavailable',- );+ await resumeAnsweredStep(FORM_STEP);+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.tsindex dd1b0c74c28..50d8e7f9213 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,6 +1,5 @@import { Injectable } from '@nestjs/common';-import { msg } from '@lingui/core/macro';import { type ActorMetadata } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';import { StepStatus } from 'twenty-shared/workflow';@@ -8,17 +7,10 @@ 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 {- WorkflowVersionStepException,- WorkflowVersionStepExceptionCode,-} from 'src/modules/workflow/common/exceptions/workflow-version-step.exception';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 { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';import { isWorkflowFormAction } from 'src/modules/workflow/workflow-executor/workflow-actions/form/guards/is-workflow-form-action.guard';import {WorkflowRunException,@@ -44,7 +36,6 @@ export class WorkflowRunnerWorkspaceService {private readonly workflowThrottlingWorkspaceService: WorkflowThrottlingWorkspaceService,private readonly coreWorkflowRunnerService: CoreWorkflowRunnerService,private readonly workflowVersionCoreSyncService: WorkflowVersionCoreSyncService,- private readonly workflowAgentConversationWorkspaceService: WorkflowAgentConversationWorkspaceService,) {}async run({@@ -102,44 +93,34 @@ 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({+ // Called once every call a step's conversation waits on is answered: a+ // form step completes with its answer, while an agent step stays PENDING+ // until the resume job claims it and continues its conversation.+ async resumeAnsweredStep({workspaceId,- stepId,workflowRunId,+ step,+ threadId,response,}: {workspaceId: string;- stepId: string;workflowRunId: string;+ step: WorkflowAction;+ threadId: string;response: Record<string, unknown>;- }): Promise<boolean> {- const workflowRun =- await this.workflowRunWorkspaceService.getWorkflowRunOrFail({- workflowRunId,- workspaceId,- });-- const step = workflowRun.state?.flow?.steps?.find(- (step) => step.id === stepId,- );-- if (!isDefined(step)) {- throw new WorkflowVersionStepException(- 'Step not found',- WorkflowVersionStepExceptionCode.NOT_FOUND,- );- }-+ }): Promise<void> {if (!isWorkflowFormAction(step)) {- throw new WorkflowVersionStepException(- 'Step is not a form',- WorkflowVersionStepExceptionCode.INVALID_REQUEST,+ await this.messageQueueService.add<RunWorkflowJobData>(+ RunWorkflowJob.name,{- userFriendlyMessage: msg`Step is not a form`,+ workspaceId,+ workflowRunId,+ stepToResume: { stepId: step.id, threadId },},+ buildRunWorkflowJobOptions(workflowRunId),);++ return;}const enrichedResponse =@@ -153,76 +134,23 @@ export class WorkflowRunnerWorkspaceService {const hasCompletedStep =await this.workflowRunWorkspaceService.updateStepInfoIfPending({- stepId,+ stepId: step.id,stepInfo: {status: StepStatus.SUCCESS,result: enrichedResponse,},- inputAskResponse: enrichedResponse,+ expectedThreadId: threadId,workspaceId,workflowRunId,});- if (!hasCompletedStep) {- return false;- }-- await this.resume({- workspaceId,- workflowRunId,- lastExecutedStepId: stepId,- });-- return true;- }-- // The step stays PENDING until the resume job claims it in its- // conversation.- async resumeAnsweredAgentStep({- workspaceId,- workflowRunId,- stepId,- threadId,- toolPart,- toolResult,- answerText,- senderUserWorkspaceId,- }: {- workspaceId: string;- workflowRunId: string;- stepId: string;- threadId: string;- toolPart: AnsweredToolPart;- toolResult: Record<string, unknown>;- answerText: string;- senderUserWorkspaceId: string;- }): Promise<void> {- const { hasAwaitingToolCalls } =- await this.workflowAgentConversationWorkspaceService.recordAnswer({+ if (hasCompletedStep) {+ await this.resume({workspaceId,- threadId,- toolPart,- toolResult,- answerText,- senderUserWorkspaceId,+ workflowRunId,+ lastExecutedStepId: step.id,});-- // 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;}-- 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/src/modules/workspace-member/standard-objects/workspace-member.workspace-entity.ts b/packages/twenty-server/src/modules/workspace-member/standard-objects/workspace-member.workspace-entity.tsindex 77273aa12d4..e487e3f9b23 100644--- a/packages/twenty-server/src/modules/workspace-member/standard-objects/workspace-member.workspace-entity.ts+++ b/packages/twenty-server/src/modules/workspace-member/standard-objects/workspace-member.workspace-entity.ts@@ -1,4 +1,3 @@-import { type InputAskWorkspaceEntity } from 'src/modules/input-ask/standard-objects/input-ask.workspace-entity';import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';import { registerEnumType } from '@nestjs/graphql';@@ -81,7 +80,6 @@ export class WorkspaceMemberWorkspaceEntity extends BaseWorkspaceEntity {agentMessages: Relation<AgentMessageWorkspaceEntity[]>;agentChatThreads: Relation<AgentChatThreadWorkspaceEntity[]>;- inputAsks: Relation<InputAskWorkspaceEntity[]>;ownedOpportunities: Relation<OpportunityWorkspaceEntity[]>;searchVector: string;numberFormat: 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-tool-call.integration-spec.tssimilarity index 73%rename from packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-ask.integration-spec.tsrename to packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-tool-call.integration-spec.tsindex 1b05961b882..e35efacc760 100644--- 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-tool-call.integration-spec.ts@@ -1,7 +1,7 @@import { randomUUID } from 'node:crypto';import { parse } from 'graphql';-import { answerAsk } from 'test/integration/graphql/suites/workflow/utils/answer-ask.util';+import { answerToolCall } from 'test/integration/graphql/suites/workflow/utils/answer-tool-call.util';import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';import { destroyAgentChatThread } from 'test/integration/utils/destroy-agent-chat-thread.util';import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';@@ -13,7 +13,6 @@ import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-executimport { 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';@@ -34,10 +33,9 @@ const QUESTIONS = [// 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', () => {+describe('Answering a chat tool call', () => {const threadId = randomUUID();let chat: AgentChatService;- let inputAsks: InputAskWorkspaceService;let enqueueStream: jest.SpyInstance;const spies: jest.SpyInstance[] = [];@@ -73,35 +71,28 @@ describe('Answering a chat tool call through its Ask', () => {})) 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,- },- });- }+ // Written in the same update as the turn's totals.+ await global.testDataSource.query(+ `UPDATE "${schema}"."agentChatThread" SET "pendingQuestionMessageId" = $1 WHERE id = $2`,+ [assistantMessageId, threadId],+ );return { assistantMessageId };};- const answerToolCallAsk = (toolCallId: string) =>- answerAsk({- ask: { threadId, toolCallId },+ const answerQuestions = (toolCallId: string) =>+ answerToolCall({+ toolCall: { threadId, toolCallId },response: { answers: [{ questionIndex: 0, selectedOptionIndices: [1] }] },});- const readAsk = async (toolCallId: string) =>+ const readPendingQuestionMessageId = async () =>(await global.testDataSource.query(- `SELECT status, response FROM "${schema}"."inputAsk" WHERE "threadId" = $1 AND "toolCallId" = $2`,- [threadId, toolCallId],+ `SELECT "pendingQuestionMessageId" FROM "${schema}"."agentChatThread" WHERE id = $1`,+ [threadId],)- )[0];+ )[0].pendingQuestionMessageId;const readToolCallStatus = async (toolCallId: string) =>(@@ -121,9 +112,6 @@ describe('Answering a chat tool call through its Ask', () => {beforeAll(async () => {chat = getAppProviderByClassName<AgentChatService>('AgentChatService');- inputAsks = getAppProviderByClassName<InputAskWorkspaceService>(- 'InputAskWorkspaceService',- );const aiModelRegistryService =getAppProviderByClassName<AiModelRegistryService>(@@ -165,64 +153,61 @@ describe('Answering a chat tool call through its Ask', () => {await stopStream();});- it('answers the Ask once, records the answer and resumes the chat', async () => {- await pauseOnQuestions('call-answered');+ it('answers the call once, records the answer, stops waiting and resumes the chat', async () => {+ const { assistantMessageId } = await pauseOnQuestions('call-answered');- expect(await readAsk('call-answered')).toEqual({- status: 'PENDING',- response: null,- });+ expect(await readPendingQuestionMessageId()).toBe(assistantMessageId);- const response = await answerToolCallAsk('call-answered');+ const response = await answerQuestions('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(response.body.data.answerToolCall.streamId).toEqual(+ expect.any(String),+ );expect(await readToolCallStatus('call-answered')).toBe('answered');+ expect(await readPendingQuestionMessageId()).toBeNull();expect(enqueueStream).toHaveBeenLastCalledWith(expect.any(String),expect.objectContaining({threadId,- streamId: response.body.data.answerAsk.streamId,+ streamId: response.body.data.answerToolCall.streamId,userWorkspaceId,}),);await stopStream();- const second = await answerToolCallAsk('call-answered');+ const second = await answerQuestions('call-answered');- expect(JSON.stringify(second.body.errors)).toContain('ASK_NOT_PENDING');+ expect(JSON.stringify(second.body.errors)).toContain(+ 'TOOL_CALL_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');+ const first = await answerQuestions('call-first');expect(first.body.errors).toBeUndefined();- expect(first.body.data.answerAsk.streamId).toBeNull();- expect(await readAsk('call-first')).toMatchObject({ status: 'ANSWERED' });+ expect(first.body.data.answerToolCall.streamId).toBeNull();expect(await readToolCallStatus('call-first')).toBe('answered');- expect(await readAsk('call-last')).toMatchObject({ status: 'PENDING' });+ expect(await readToolCallStatus('call-last')).toBe('pending');+ expect(await readPendingQuestionMessageId()).not.toBeNull();expect(enqueueStream).not.toHaveBeenCalled();- const last = await answerToolCallAsk('call-last');+ const last = await answerQuestions('call-last');expect(last.body.errors).toBeUndefined();- expect(last.body.data.answerAsk.streamId).toEqual(expect.any(String));+ expect(last.body.data.answerToolCall.streamId).toEqual(expect.any(String));+ expect(await readPendingQuestionMessageId()).toBeNull();expect(enqueueStream).toHaveBeenCalledTimes(1);expect(enqueueStream).toHaveBeenLastCalledWith(expect.any(String),expect.objectContaining({threadId,- streamId: last.body.data.answerAsk.streamId,+ streamId: last.body.data.answerToolCall.streamId,}),);});@@ -250,16 +235,11 @@ describe('Answering a chat tool call through its Ask', () => {queued: false,streamId: expect.any(String),});- expect(await readAsk('call-legacy')).toEqual({- status: 'ANSWERED',- response: {- answers: [{ questionIndex: 0, selectedOptionIndices: [1] }],- },- });+ expect(await readToolCallStatus('call-legacy')).toBe('answered');expect(enqueueStream).toHaveBeenCalledTimes(1);});- it('cancels every pending Ask when a message is sent instead of the answers', async () => {+ it('closes every pending call when a message is sent instead of the answers', async () => {await pauseOnQuestions('call-skipped-first', 'call-skipped-last');const response = await makeMetadataApiRequest({@@ -274,16 +254,16 @@ describe('Answering a chat tool call through its Ask', () => {expect(response.body.errors).toBeUndefined();expect(response.body.data.sendChatMessage.queued).toBe(false);+ expect(await readPendingQuestionMessageId()).toBeNull();+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');+ const lateAnswer = await answerQuestions('call-skipped-first');- expect(JSON.stringify(lateAnswer.body.errors)).toContain('ASK_NOT_PENDING');+ expect(JSON.stringify(lateAnswer.body.errors)).toContain(+ 'TOOL_CALL_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.tsindex 4331f8fa480..1fee5e9a477 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,15 +1,10 @@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 { PermissionFlagType } from 'twenty-shared/constants';-import {- FeatureFlagKey,- FieldMetadataType,- WorkflowVisibility,-} from 'twenty-shared/types';+import { FeatureFlagKey, FieldMetadataType } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';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';@@ -30,15 +25,10 @@ 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 { answerToolCall } from 'test/integration/graphql/suites/workflow/utils/answer-tool-call.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';+import { type AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';import { type ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';import { type AutomatedTriggerWorkspaceService } from 'src/modules/workflow/workflow-trigger/automated-trigger/automated-trigger.workspace-service';@@ -750,8 +740,8 @@ describe('core workflow execution and queue compatibility (e2e)', () => {await waitForStep(runId, form.id, 'PENDING');await migratePendingRun(fixture, runId);await clearDefinitions(fixture);- const response = await answerAsk({- ask: { workflowRunId: runId, stepId: form.id },+ const response = await answerToolCall({+ toolCall: { workflowRunId: runId, stepId: form.id },response: { answer: 'From the stored form' },});@@ -790,7 +780,10 @@ describe('core workflow execution and queue compatibility (e2e)', () => {stepId: string;answer: string;}) =>- answerAsk({ ask: { workflowRunId: runId, stepId }, response: { answer } });+ answerToolCall({+ toolCall: { workflowRunId: runId, stepId },+ response: { answer },+ });it('still answers a form through the deprecated submitFormStep', async () => {const finalStep = emptyStep();@@ -834,22 +827,42 @@ describe('core workflow execution and queue compatibility (e2e)', () => {},);- expect(JSON.stringify(second.body.errors)).toContain('ASK_NOT_PENDING');+ expect(JSON.stringify(second.body.errors)).toContain(+ 'TOOL_CALL_NOT_PENDING',+ );});- describe('the Ask a form step opens', () => {- const getInputAsks = async (runId: string) =>- global.testDataSource.query(- `SELECT name, "stepId", status, form, response, "answeredAt" FROM "${schema}"."inputAsk" WHERE "workflowRunId" = $1`,- [runId],- );-+ describe('the conversation a form step records', () => {const approvalForm = (nextStepIds: string[]): WorkflowAction => ({...formStep(nextStepIds),name: 'Approve the discount',});- it('opens while the form waits and is answered on submit', async () => {+ // The form's call is named after the step, in the conversation the step's+ // current execution recorded.+ const getFormConversation = async (runId: string, stepId: string) => {+ const threadId = (await getRun(runId)).state.stepInfos[stepId].threadId;+ const [thread] = await global.testDataSource.query(+ `SELECT title, "pendingQuestionMessageId" FROM "${schema}"."agentChatThread" WHERE id = $1`,+ [threadId],+ );+ const [part] = await global.testDataSource.query(+ `SELECT part."toolName", part."toolInput", part."toolOutput" FROM "${schema}"."agentMessagePart" part JOIN "${schema}"."agentMessage" message ON message.id = part."messageId" WHERE message."threadId" = $1 AND part."toolCallId" = $2`,+ [threadId, stepId],+ );++ return {+ threadId,+ title: thread?.title,+ isWaiting: isDefined(thread?.pendingQuestionMessageId),+ toolName: part?.toolName,+ toolInput: part?.toolInput,+ status: part?.toolOutput?.result?.status,+ values: part?.toolOutput?.result?.values,+ };+ };++ it('asks for the fields in a request_form call while the form waits, and records the answer on submit', async () => {const finalStep = emptyStep();const form = approvalForm([finalStep.id]);const fixture = await createFixture({@@ -860,18 +873,12 @@ describe('core workflow execution and queue compatibility (e2e)', () => {await waitForStep(runId, form.id, 'PENDING');- const [pendingInputAsk] = await getInputAsks(runId);-- expect(pendingInputAsk).toMatchObject({- name: 'Approve the discount',- stepId: form.id,- status: 'PENDING',- response: null,- answeredAt: null,- });- expect(pendingInputAsk.form).toEqual({- kind: 'formFields',- fields: form.settings.input,+ expect(await getFormConversation(runId, form.id)).toMatchObject({+ title: 'Approve the discount',+ isWaiting: true,+ toolName: 'request_form',+ toolInput: { fields: form.settings.input },+ status: 'pending',});const response = await submitForm({@@ -883,207 +890,14 @@ describe('core workflow execution and queue compatibility (e2e)', () => {expect(response.body.errors).toBeUndefined();await waitForRun(runId, 'COMPLETED');- const answeredInputAsks = await getInputAsks(runId);-- expect(answeredInputAsks).toHaveLength(1);- expect(answeredInputAsks[0]).toMatchObject({- stepId: form.id,- status: 'ANSWERED',- response: { answer: 'Approved' },- });- expect(answeredInputAsks[0].answeredAt).not.toBeNull();- });-- 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,- },- });- });-- afterAll(async () => {- await updateWorkspaceMemberRole({- expectToFail: false,- input: {- roleId: originalMemberRoleId,- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,- },- });- await deleteOneRole({- expectToFail: false,- input: { idToDelete: workflowsRoleId },- });- });-- // 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],- );-- 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();- });-- 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);-- await waitForStep(runId, form.id, 'PENDING');-- 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);+ expect(await getFormConversation(runId, form.id)).toMatchObject({+ isWaiting: false,+ status: 'answered',+ values: { answer: 'Approved' },});});- it('refuses a submission whose Ask cannot record it, leaving the form waiting', async () => {+ it('refuses a submission whose answer cannot be recorded, leaving the form waiting', async () => {const finalStep = emptyStep();const form = approvalForm([finalStep.id]);const fixture = await createFixture({@@ -1094,14 +908,12 @@ describe('core workflow execution and queue compatibility (e2e)', () => {await waitForStep(runId, form.id, 'PENDING');- const answer = jest+ const recordToolCallAnswer = jest.spyOn(- getAppProviderByClassName<InputAskWorkspaceService>(- 'InputAskWorkspaceService',- ),- 'answer',+ getAppProviderByClassName<AgentChatService>('AgentChatService'),+ 'recordToolCallAnswer',)- .mockRejectedValueOnce(new Error('Ask write failed'));+ .mockRejectedValueOnce(new Error('Answer write failed'));const refused = await submitForm({runId,@@ -1109,25 +921,22 @@ describe('core workflow execution and queue compatibility (e2e)', () => {answer: 'Approved',});- answer.mockRestore();+ recordToolCallAnswer.mockRestore();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 },- ]);+ expect(await getFormConversation(runId, form.id)).toMatchObject({+ isWaiting: true,+ status: 'pending',+ });expect((await submitForm({ runId, stepId: form.id, answer: 'Approved' })).body.errors,).toBeUndefined();await waitForRun(runId, 'COMPLETED');-- expect(await getInputAsks(runId)).toMatchObject([- { status: 'ANSWERED', response: { answer: 'Approved' } },- ]);});it('refuses a second submission and keeps the first answer', async () => {@@ -1156,19 +965,21 @@ describe('core workflow execution and queue compatibility (e2e)', () => {answer: 'Approved again',});- expect(JSON.stringify(second.body.errors)).toContain('ASK_NOT_PENDING');+ expect(JSON.stringify(second.body.errors)).toContain(+ 'TOOL_CALL_NOT_PENDING',+ );expect((await getRun(runId)).state.stepInfos[form.id].result).toEqual({answer: 'Approved',});- expect(await getInputAsks(runId)).toMatchObject([- { status: 'ANSWERED', response: { answer: 'Approved' } },- ]);+ expect(await getFormConversation(runId, form.id)).toMatchObject({+ values: { answer: 'Approved' },+ });});// Every iteration of a loop re-executes the same step in the same run, so- // the Ask keyed on the run and the step is reused. Without reopening it,- // the first iteration's answer would stand for the second.- it('reopens for each iteration of a form inside a loop', async () => {+ // each records its own conversation and one iteration's answer never+ // stands for the next.+ it('records a conversation for each iteration of a form inside a loop', async () => {const afterLoop = emptyStep();const form = approvalForm([]);const iterator: WorkflowAction = {@@ -1193,7 +1004,11 @@ describe('core workflow execution and queue compatibility (e2e)', () => {const runId = await runFixture(fixture);await waitForStep(runId, form.id, 'PENDING');- expect(await getInputAsks(runId)).toMatchObject([{ status: 'PENDING' }]);++ const { threadId: firstThreadId } = await getFormConversation(+ runId,+ form.id,+ );const first = await submitForm({runId,@@ -1204,14 +1019,12 @@ describe('core workflow execution and queue compatibility (e2e)', () => {expect(first.body.errors).toBeUndefined();await waitForStep(runId, form.id, 'PENDING');- const reopenedInputAsks = await getInputAsks(runId);+ const secondConversation = await getFormConversation(runId, form.id);- expect(reopenedInputAsks).toHaveLength(1);- expect(reopenedInputAsks[0]).toMatchObject({- stepId: form.id,- status: 'PENDING',- response: null,- answeredAt: null,+ expect(secondConversation.threadId).not.toBe(firstThreadId);+ expect(secondConversation).toMatchObject({+ isWaiting: true,+ status: 'pending',});const second = await submitForm({@@ -1222,12 +1035,12 @@ describe('core workflow execution and queue compatibility (e2e)', () => {expect(second.body.errors).toBeUndefined();await waitForRun(runId, 'COMPLETED');- expect(await getInputAsks(runId)).toMatchObject([- { status: 'ANSWERED', response: { answer: 'Second item' } },- ]);+ expect(await getFormConversation(runId, form.id)).toMatchObject({+ values: { answer: 'Second item' },+ });});- it('is canceled when its run ends before anyone answers, and stays canceled', async () => {+ it('closes the call when its run ends before anyone answers', async () => {const finalStep = emptyStep();const form = approvalForm([finalStep.id]);const fixture = await createFixture({@@ -1237,7 +1050,6 @@ describe('core workflow execution and queue compatibility (e2e)', () => {const runId = await runFixture(fixture);await waitForStep(runId, form.id, 'PENDING');- expect(await getInputAsks(runId)).toMatchObject([{ status: 'PENDING' }]);const response = await workflowGraphqlRequest('mutation Stop($id: UUID!) { stopWorkflowRun(workflowRunId: $id) { id status } }',@@ -1246,7 +1058,10 @@ describe('core workflow execution and queue compatibility (e2e)', () => {expect(response.body.errors).toBeUndefined();await waitForRun(runId, 'STOPPED');- expect(await getInputAsks(runId)).toMatchObject([{ status: 'CANCELED' }]);+ expect(await getFormConversation(runId, form.id)).toMatchObject({+ isWaiting: false,+ status: 'skipped',+ });const late = await submitForm({runId,@@ -1254,10 +1069,9 @@ describe('core workflow execution and queue compatibility (e2e)', () => {answer: 'Too late',});- expect(JSON.stringify(late.body.errors)).toContain('ASK_NOT_PENDING');- expect(await getInputAsks(runId)).toMatchObject([- { status: 'CANCELED', response: null },- ]);+ expect(JSON.stringify(late.body.errors)).toContain(+ 'TOOL_CALL_NOT_PENDING',+ );const run = await getRun(runId);@@ -1290,7 +1104,9 @@ describe('core workflow execution and queue compatibility (e2e)', () => {answer: 'While stopping',});- expect(JSON.stringify(response.body.errors)).toContain('ASK_NOT_PENDING');+ expect(JSON.stringify(response.body.errors)).toContain(+ 'TOOL_CALL_NOT_PENDING',+ );expect((await getRun(runId)).state.stepInfos[form.id].status).toBe('PENDING',);@@ -1376,12 +1192,32 @@ describe('core workflow execution and queue compatibility (e2e)', () => {.mockResolvedValueOnce(askingResult).mockResolvedValueOnce(replyingResult);- const getThreadInputAsks = async (threadId: string) =>- global.testDataSource.query(- `SELECT name, status, "toolCallId", "stepId", "workflowRunId", form, response FROM "${schema}"."inputAsk" WHERE "threadId" = $1`,+ // Each call the conversation waits on, and whether it still waits.+ const getToolCalls = async (threadId: string) => {+ const [thread] = await global.testDataSource.query(+ `SELECT "pendingQuestionMessageId" FROM "${schema}"."agentChatThread" WHERE id = $1`,+ [threadId],+ );+ const parts = await global.testDataSource.query(+ `SELECT part."toolCallId", part."toolOutput" FROM "${schema}"."agentMessagePart" part JOIN "${schema}"."agentMessage" message ON message.id = part."messageId" WHERE message."threadId" = $1 AND part."toolName" = 'ask_questions' ORDER BY part."toolCallId"`,[threadId],);+ return {+ isWaiting: isDefined(thread.pendingQuestionMessageId),+ calls: parts.map(+ (part: {+ toolCallId: string;+ toolOutput: { result: Record<string, unknown> };+ }) => ({+ toolCallId: part.toolCallId,+ status: part.toolOutput.result.status,+ answers: part.toolOutput.result.answers,+ }),+ ),+ };+ };+const getConversation = async (threadId: string) => {const messages = await global.testDataSource.query(`SELECT id, role FROM "${schema}"."agentMessage" WHERE "threadId" = $1 ORDER BY "processedAt", "createdAt"`,@@ -1415,8 +1251,8 @@ describe('core workflow execution and queue compatibility (e2e)', () => {threadId: string;toolCallId?: string;}) =>- answerAsk({- ask: { threadId, toolCallId },+ answerToolCall({+ toolCall: { threadId, toolCallId },response: {answers: [{ questionIndex: 0, selectedOptionIndices: [0] }],},@@ -1459,22 +1295,15 @@ describe('core workflow execution and queue compatibility (e2e)', () => {expect((await getRun(runId)).state.stepInfos[finalStep.id].status).toBe('NOT_STARTED',);- expect(await getThreadInputAsks(threadId)).toEqual([- {- name: 'Send the quote to the customer?',- status: 'PENDING',- toolCallId: 'ask-1',- stepId: agent.id,- workflowRunId: runId,- form: { kind: 'questions', questions: QUESTIONS },- response: null,- },- ]);+ expect(await getToolCalls(threadId)).toEqual({+ isWaiting: true,+ calls: [{ toolCallId: 'ask-1', status: 'pending' }],+ });const response = await answer({ threadId });expect(response.body.errors).toBeUndefined();- expect(response.body.data.answerAsk.streamId).toBeNull();+ expect(response.body.data.answerToolCall.streamId).toBeNull();const run = await waitForRun(runId, 'COMPLETED');@@ -1495,14 +1324,16 @@ describe('core workflow execution and queue compatibility (e2e)', () => {const { messages, questionPart } = await getConversation(threadId);expect(questionPart.toolOutput.result.status).toBe('answered');- expect(await getThreadInputAsks(threadId)).toMatchObject([- {- status: 'ANSWERED',- response: {+ expect(await getToolCalls(threadId)).toEqual({+ isWaiting: false,+ calls: [+ {+ toolCallId: 'ask-1',+ status: 'answered',answers: [{ questionIndex: 0, selectedOptionIndices: [0] }],},- },- ]);+ ],+ });expect(messages.map(({ role }: { role: string }) => role)).toEqual(['user','assistant',@@ -1520,9 +1351,11 @@ describe('core workflow execution and queue compatibility (e2e)', () => {const second = await answer({ threadId });- expect(JSON.stringify(second.body.errors)).toContain('ASK_NOT_PENDING');- expect(await getThreadInputAsks(threadId)).toMatchObject([- { status: 'ANSWERED' },+ expect(JSON.stringify(second.body.errors)).toContain(+ 'TOOL_CALL_NOT_PENDING',+ );+ expect((await getToolCalls(threadId)).calls).toMatchObject([+ { status: 'answered' },]);});@@ -1564,19 +1397,13 @@ describe('core workflow execution and queue compatibility (e2e)', () => {.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' },- ]),- );+ expect(await getToolCalls(threadId)).toEqual({+ isWaiting: true,+ calls: [+ { toolCallId: 'ask-1', status: 'pending' },+ { toolCallId: 'ask-2', status: 'pending' },+ ],+ });const first = await answer({ threadId, toolCallId: 'ask-1' });@@ -1605,7 +1432,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {).not.toContain('"pending"');});- it('refuses an answer once the run is stopped, whose end canceled the Ask', async () => {+ it('refuses an answer once the run is stopped, whose end closed the call', async () => {mockAgent();const { runId, agent, threadId } = await startAskingRun();@@ -1617,15 +1444,15 @@ describe('core workflow execution and queue compatibility (e2e)', () => {const response = await answer({ threadId });- expect(JSON.stringify(response.body.errors)).toContain('ASK_NOT_PENDING');+ expect(JSON.stringify(response.body.errors)).toContain(+ 'TOOL_CALL_NOT_PENDING',+ );const { messages, questionPart } = await getConversation(threadId);- expect(questionPart.toolOutput.result.status).not.toBe('answered');+ expect(questionPart.toolOutput.result.status).toBe('skipped');expect(messages).toHaveLength(2);- expect(await getThreadInputAsks(threadId)).toMatchObject([- { status: 'CANCELED', response: null },- ]);+ expect((await getToolCalls(threadId)).isWaiting).toBe(false);expect((await getRun(runId)).state.stepInfos[agent.id].status).toBe('FAILED',);@@ -1695,22 +1522,20 @@ describe('core workflow execution and queue compatibility (e2e)', () => {expect(executeAgent).toHaveBeenCalledTimes(2);});- it('refuses the answer, leaving the question open, when its Ask cannot record it', async () => {+ it('refuses the answer, leaving the question open, when it cannot be recorded', async () => {mockAgent();const { runId, agent, threadId } = await startAskingRun();- const inputAskAnswer = jest+ const recordToolCallAnswer = jest.spyOn(- getAppProviderByClassName<InputAskWorkspaceService>(- 'InputAskWorkspaceService',- ),- 'answer',+ getAppProviderByClassName<AgentChatService>('AgentChatService'),+ 'recordToolCallAnswer',)- .mockRejectedValueOnce(new Error('Ask write failed'));+ .mockRejectedValueOnce(new Error('Answer write failed'));const refused = await answer({ threadId });- inputAskAnswer.mockRestore();+ recordToolCallAnswer.mockRestore();expect(refused.body.errors).toBeDefined();expect((await getRun(runId)).state.stepInfos[agent.id]).toMatchObject({@@ -1718,9 +1543,10 @@ describe('core workflow execution and queue compatibility (e2e)', () => {threadId,});expect((await getConversation(threadId)).messages).toHaveLength(2);- expect(await getThreadInputAsks(threadId)).toMatchObject([- { status: 'PENDING', response: null },- ]);+ expect(await getToolCalls(threadId)).toEqual({+ isWaiting: true,+ calls: [{ toolCallId: 'ask-1', status: 'pending' }],+ });expect((await answer({ threadId })).body.errors).toBeUndefined();await waitForRun(runId, 'COMPLETED');@@ -1745,51 +1571,12 @@ describe('core workflow execution and queue compatibility (e2e)', () => {expect(failedAnswer.body.errors).toBeDefined();await waitForRun(runId, 'FAILED');- expect(await getThreadInputAsks(threadId)).toMatchObject([- { status: 'ANSWERED' },+ expect((await getToolCalls(threadId)).calls).toMatchObject([+ { status: 'answered' },]);expect(JSON.stringify((await answer({ threadId })).body.errors),- ).toContain('ASK_NOT_PENDING');- });-- it('keeps the Ask answered when the run is stopped while the answer is accepted', async () => {- mockAgent();- const { runId, threadId } = await startAskingRun();-- 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 });-- await stop;- spy.mockRestore();-- expect(response.body.errors).toBeUndefined();- await waitForRun(runId, 'STOPPED');- expect(await getThreadInputAsks(threadId)).toMatchObject([- { status: 'ANSWERED' },- ]);+ ).toContain('TOOL_CALL_NOT_PENDING');});});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.tsindex cb9b7ef2326..94e939ed144 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,4 +1,3 @@-import { StepStatus } from 'twenty-shared/workflow';import { randomUUID } from 'node:crypto';import request from 'supertest';@@ -998,154 +997,6 @@ describe('core workflow visibility (e2e)', () => {});});- // An Ask has no grants of its own either: whoever reads the run reads its- // questions, and nobody else.- describe('the Ask an agent question records on a run', () => {- let askCoreWorkflowId: string;- let askWorkspaceWorkflowId: string;- let threadId: string;-- const QUESTIONS = [- {- header: 'Quote',- question: 'Send the quote to the customer?',- options: [{ label: 'Send it' }, { label: 'Hold it' }],- },- ];-- const readAsks = async (- requester: (query: string, variables?: object) => request.Test,- ) => {- const response = await requester(- `- query ReadAsks($threadId: UUID!) {- inputAsks(filter: { threadId: { eq: $threadId } }) {- edges {- node {- id- status- }- }- }- }- `,- { threadId },- );-- expect(response.body.errors).toBeUndefined();-- return response.body.data.inputAsks.edges;- };-- beforeAll(async () => {- let workspaceWorkflowVersionId: string;-- ({- coreWorkflowId: askCoreWorkflowId,- workspaceWorkflowId: askWorkspaceWorkflowId,- workspaceWorkflowVersionId,- } = await createActiveManualWorkflow('Workflow With A Question'));-- const runResponse = await workflowGraphqlRequest(LEGACY_RUN_MUTATION, {- input: { workflowVersionId: workspaceWorkflowVersionId },- });-- expect(runResponse.body.errors).toBeUndefined();-- const askRunId: string =- runResponse.body.data.runWorkflowVersion.workflowRunId;- const [{ state }] = await global.testDataSource.query(- `SELECT state FROM "${getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID)}"."workflowRun" WHERE id = $1`,- [askRunId],- );- const askStepId = state.flow.steps[0].id as string;-- const conversationService =- getAppProviderByClassName<WorkflowAgentConversationWorkspaceService>(- 'WorkflowAgentConversationWorkspaceService',- );-- const recordedConversation = await conversationService.recordExecution({- workspaceId: SEED_APPLE_WORKSPACE_ID,- workflowRunId: askRunId,- stepId: askStepId,- title: 'Draft the quote',- agentId: null,- prompt: 'Draft the quote',- initiatorUserWorkspaceId: null,- executionResult: {- isPaused: true,- steps: [- {- content: [- {- type: 'tool-call',- toolCallId: 'ask-1',- toolName: 'ask_questions',- input: { questions: QUESTIONS },- },- {- type: 'tool-result',- toolCallId: 'ask-1',- toolName: 'ask_questions',- input: { questions: QUESTIONS },- output: {- success: true,- message: 'Awaiting an answer.',- result: { questions: QUESTIONS, status: 'pending' },- },- },- ],- },- ] as AgentExecutionResult['steps'],- },- });-- 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 () => {- if (isDefined(askWorkspaceWorkflowId)) {- await setVisibility(askCoreWorkflowId, WorkflowVisibility.WORKSPACE);- await workflowGraphqlRequest(DESTROY_WORKFLOW_MUTATION, {- id: askWorkspaceWorkflowId,- });- }- });-- it('is readable by another member while the workflow is visible to the workspace', async () => {- expect(- (await setVisibility(askCoreWorkflowId, WorkflowVisibility.WORKSPACE))- .body.errors,- ).toBeUndefined();- // Its status depends on whether the run has finished meanwhile, which- // has nothing to do with who may read it.- expect(await readAsks(asOtherMember)).toHaveLength(1);- });-- it('is hidden from another member once the workflow is private, but not from its creator', async () => {- expect(- (await setVisibility(askCoreWorkflowId, WorkflowVisibility.PRIVATE))- .body.errors,- ).toBeUndefined();- expect(await readAsks(asOtherMember)).toEqual([]);- expect(await readAsks(workflowGraphqlRequest)).toHaveLength(1);- });- });-// Removing a member deletes their membership, and the database then clears// the creator of every workflow they created.describe('the runs of a private workflow whose creator is removed from the workspace', () => {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.tsindex 4bad87bd2f7..6724e77d743 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@@ -14,6 +14,7 @@ import {type WorkflowDelayAction,type WorkflowFormAction,} from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';+import { answerToolCall } from 'test/integration/graphql/suites/workflow/utils/answer-tool-call.util';import { updateWorkflowVersionTrigger } from 'test/integration/graphql/suites/workflow/utils/update-workflow-version-trigger.util';import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';@@ -324,32 +325,13 @@ 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 AnswerAsk($input: AnswerAskInput!) {- answerAsk(input: $input) {- streamId- }- }- `,- variables: {- input: {- askId: formAskId,- response: { answer: 'Submitted from integration test' },- },- },- });+ const submitFormResponse = await answerToolCall({+ toolCall: { workflowRunId: createdWorkflowRunId, stepId: formStepId! },+ response: { answer: 'Submitted from integration test' },+ });expect(submitFormResponse.body.errors).toBeUndefined();- expect(submitFormResponse.body.data.answerAsk.streamId).toBeNull();+ expect(submitFormResponse.body.data.answerToolCall.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.tsindex 16bf5a2f7f6..7108939e8f4 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,5 +1,5 @@import request from 'supertest';-import { answerAsk } from 'test/integration/graphql/suites/workflow/utils/answer-ask.util';+import { answerToolCall } from 'test/integration/graphql/suites/workflow/utils/answer-tool-call.util';import {destroyWorkflowRun,getWorkflowRun,@@ -270,8 +270,8 @@ describe('Quick Lead Workflow (e2e)', () => {companyDomain: `https://test-${testId}.example.com`,};- const submitFormResponse = await answerAsk({- ask: {+ const submitFormResponse = await answerToolCall({+ toolCall: {workflowRunId: testWorkflowRunId as string,stepId: FORM_STEP_ID,},@@ -279,7 +279,7 @@ describe('Quick Lead Workflow (e2e)', () => {});expect(submitFormResponse.body.errors).toBeUndefined();- expect(submitFormResponse.body.data.answerAsk.streamId).toBeNull();+ expect(submitFormResponse.body.data.answerToolCall.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.tsdeleted file mode 100644index f4868d917d8..00000000000--- a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/answer-ask.util.ts+++ /dev/null@@ -1,40 +0,0 @@-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/graphql/suites/workflow/utils/answer-tool-call.util.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/answer-tool-call.util.tsnew file mode 100644index 00000000000..f4c5997f47d--- /dev/null+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/answer-tool-call.util.ts@@ -0,0 +1,47 @@+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 ToolCallLocation =+ | { workflowRunId: string; stepId: string }+ | { threadId: string; toolCallId: string };++// A form step's call is named after the step, in the conversation its current+// execution recorded.+const findFormStepThreadId = async ({+ workflowRunId,+ stepId,+}: {+ workflowRunId: string;+ stepId: string;+}): Promise<string | undefined> => {+ const [row] = await global.testDataSource.query(+ `SELECT state->'stepInfos'->$2->>'threadId' AS "threadId" FROM "${getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID)}"."workflowRun" WHERE id = $1`,+ [workflowRunId, stepId],+ );++ return row?.threadId;+};++export const answerToolCall = async ({+ toolCall,+ response,+}: {+ toolCall: ToolCallLocation;+ response: Record<string, unknown>;+}) =>+ workflowGraphqlRequest(+ 'mutation Answer($input: AnswerToolCallInput!) { answerToolCall(input: $input) { streamId } }',+ {+ input: {+ ...('threadId' in toolCall+ ? toolCall+ : {+ threadId: await findFormStepThreadId(toolCall),+ toolCallId: toolCall.stepId,+ }),+ response,+ },+ },+ );diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.tsindex 87fcbcddb21..0a3319d209b 100644--- a/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts+++ b/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts@@ -1,7 +1,6 @@import { type EnableCommonRecordSharingCommand } from 'src/database/commands/upgrade-version-command/2-43/2-43-workspace-command-1790312694997-enable-common-record-sharing.command';import { type AddWorkflowRunToChatThreadsCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command';import { type OpenAgentChatThreadArchivedAtWritabilityCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790672076234-open-agent-chat-thread-archived-at-writability.command';-import { type AddInputAskObjectCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790681093095-add-input-ask-object.command';import { type MoveAgentChatThreadsToRecordModelCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790751626421-move-agent-chat-threads-to-record-model.command';import { type AddChatRecordPageCommandMenuItemsCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790751626422-add-chat-record-page-command-menu-items.command';import { randomUUID } from 'node:crypto';@@ -265,9 +264,6 @@ describe('versioned agent history upgrade (integration)', () => {getAppProviderByClassName<OpenAgentChatThreadArchivedAtWritabilityCommand>('OpenAgentChatThreadArchivedAtWritabilityCommand',),- getAppProviderByClassName<AddInputAskObjectCommand>(- 'AddInputAskObjectCommand',- ),getAppProviderByClassName<MoveAgentChatThreadsToRecordModelCommand>('MoveAgentChatThreadsToRecordModelCommand',),diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790681093095-add-input-ask-object.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790681093095-add-input-ask-object.integration-spec.tsdeleted file mode 100644index 3c04ee3d756..00000000000--- a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790681093095-add-input-ask-object.integration-spec.ts+++ /dev/null@@ -1,155 +0,0 @@-import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';-import { STANDARD_OBJECTS } from 'twenty-shared/metadata';-import { MetadataReadability, MetadataWritability } from 'twenty-shared/types';-import { isDefined } from 'twenty-shared/utils';--import { type AddInputAskObjectCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790681093095-add-input-ask-object.command';-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 { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';-import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';--const RUN_ON_WORKSPACE_ARGS = {- workspaceId: SEED_APPLE_WORKSPACE_ID,- options: {},- index: 0,- total: 1,-};--const INVERSE_FIELD_UNIVERSAL_IDENTIFIERS = [- STANDARD_OBJECTS.workflowRun.fields.inputAsks.universalIdentifier,- STANDARD_OBJECTS.workspaceMember.fields.inputAsks.universalIdentifier,- STANDARD_OBJECTS.agentChatThread.fields.inputAsks.universalIdentifier,-];--describe('2-44 workspace command 1790681093095 - AddInputAskObjectCommand (integration)', () => {- let command: AddInputAskObjectCommand;- let workspaceOrmManager: WorkspaceOrmManager;- let workspaceCacheService: WorkspaceCacheService;-- const runInWorkspace = (run: () => Promise<void>) =>- workspaceOrmManager.executeInWorkspaceContext(- run,- buildSystemAuthContext(SEED_APPLE_WORKSPACE_ID),- );-- const readState = async () => {- const {- flatObjectMetadataMaps,- flatFieldMetadataMaps,- flatIndexMaps,- flatViewMaps,- } = await workspaceCacheService.getOrRecompute(SEED_APPLE_WORKSPACE_ID, [- 'flatObjectMetadataMaps',- 'flatFieldMetadataMaps',- 'flatIndexMaps',- 'flatViewMaps',- ]);- const inputAskObject =- flatObjectMetadataMaps.byUniversalIdentifier[- STANDARD_OBJECTS.inputAsk.universalIdentifier- ];-- return {- hasObject: isDefined(inputAskObject),- readability: inputAskObject?.readability,- readabilityParentFieldUniversalIdentifiers:- inputAskObject?.readabilityParentFieldUniversalIdentifiers,- writability: inputAskObject?.writability,- fieldCount: Object.values(STANDARD_OBJECTS.inputAsk.fields).filter(- ({ universalIdentifier }) =>- isDefined(- flatFieldMetadataMaps.byUniversalIdentifier[universalIdentifier],- ),- ).length,- inverseFieldCount: INVERSE_FIELD_UNIVERSAL_IDENTIFIERS.filter(- (universalIdentifier) =>- isDefined(- flatFieldMetadataMaps.byUniversalIdentifier[universalIdentifier],- ),- ).length,- indexCount: Object.values(STANDARD_OBJECTS.inputAsk.indexes).filter(- ({ universalIdentifier }) =>- isDefined(flatIndexMaps.byUniversalIdentifier[universalIdentifier]),- ).length,- viewCount: Object.values(STANDARD_OBJECTS.inputAsk.views).filter(- ({ universalIdentifier }) =>- isDefined(flatViewMaps.byUniversalIdentifier[universalIdentifier]),- ).length,- };- };-- beforeAll(async () => {- command = getAppProviderByClassName<AddInputAskObjectCommand>(- 'AddInputAskObjectCommand',- );- workspaceOrmManager = getAppProviderByClassName<WorkspaceOrmManager>(- 'WorkspaceOrmManager',- );- workspaceCacheService = getAppProviderByClassName<WorkspaceCacheService>(- 'WorkspaceCacheService',- );-- // What a workspace looks like before the command: no Ask object at all.- await runInWorkspace(() => command.down(RUN_ON_WORKSPACE_ARGS));- });-- afterAll(async () => {- await runInWorkspace(() => command.runOnWorkspace(RUN_ON_WORKSPACE_ARGS));- });-- it('starts from a workspace without the Ask object or its inverse fields', async () => {- expect(await readState()).toMatchObject({- hasObject: false,- fieldCount: 0,- inverseFieldCount: 0,- });- });-- it('changes nothing on a dry run', async () => {- await runInWorkspace(() =>- command.runOnWorkspace({- ...RUN_ON_WORKSPACE_ARGS,- options: { dryRun: true },- }),- );-- expect(await readState()).toMatchObject({ hasObject: false });- });-- it('creates the object as a fresh install has it', async () => {- await runInWorkspace(() => command.runOnWorkspace(RUN_ON_WORKSPACE_ARGS));-- expect(await readState()).toEqual({- hasObject: true,- readability: MetadataReadability.INHERITED,- readabilityParentFieldUniversalIdentifiers: [- STANDARD_OBJECTS.inputAsk.fields.workflowRun.universalIdentifier,- STANDARD_OBJECTS.inputAsk.fields.thread.universalIdentifier,- ],- writability: MetadataWritability.OPEN,- fieldCount: Object.keys(STANDARD_OBJECTS.inputAsk.fields).length,- inverseFieldCount: INVERSE_FIELD_UNIVERSAL_IDENTIFIERS.length,- indexCount: Object.keys(STANDARD_OBJECTS.inputAsk.indexes).length,- viewCount: Object.keys(STANDARD_OBJECTS.inputAsk.views).length,- });- });-- it('is a no-op when run again', async () => {- const before = await readState();-- await runInWorkspace(() => command.runOnWorkspace(RUN_ON_WORKSPACE_ARGS));-- expect(await readState()).toEqual(before);- });-- it('removes the object and its inverse fields on down', async () => {- await runInWorkspace(() => command.down(RUN_ON_WORKSPACE_ARGS));-- expect(await readState()).toMatchObject({- hasObject: false,- fieldCount: 0,- inverseFieldCount: 0,- });- });-});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.tsdeleted file mode 100644index cb894ca13a9..00000000000--- a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790714482317-open-asks-for-pending-input.integration-spec.ts+++ /dev/null@@ -1,236 +0,0 @@-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-server/test/integration/upgrade/suites/2-44-workspace-command-1790772993322-record-pending-form-conversations.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790772993322-record-pending-form-conversations.integration-spec.tsnew file mode 100644index 00000000000..6dcf9489de7--- /dev/null+++ b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790772993322-record-pending-form-conversations.integration-spec.ts@@ -0,0 +1,177 @@+import { StepStatus, WorkflowActionType } from 'twenty-shared/workflow';+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';++import { type RecordPendingFormConversationsCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790772993322-record-pending-form-conversations.command';+import { type UpgradeCommandRegistryService } from 'src/engine/core-modules/upgrade/services/upgrade-command-registry.service';+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 {+ WorkflowRunStatus,+ type WorkflowRunWorkspaceEntity,+} from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';++const RUN_ON_WORKSPACE_ARGS = {+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ options: {},+ index: 0,+ total: 1,+};++describe('2-44 workspace command 1790772993322 - RecordPendingFormConversationsCommand (integration)', () => {+ let command: RecordPendingFormConversationsCommand;+ let workspaceOrmManager: WorkspaceOrmManager;+ let workflowRun: Pick<WorkflowRunWorkspaceEntity, 'id' | 'state'>;+ let formStepId: 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 findFormThreadId = async () => {+ const { state } = await inWorkspace(() =>+ repository('workflowRun').findOneOrFail({+ where: { id: workflowRun.id },+ select: { state: true },+ }),+ );++ return state?.stepInfos?.[formStepId]?.threadId;+ };++ // A form step waiting since before this release: pending, with no+ // conversation recorded for it.+ const forgetFormConversation = () =>+ inWorkspace(() =>+ repository('workflowRun').update(workflowRun.id, {+ state: {+ ...workflowRun.state,+ stepInfos: {+ ...workflowRun.state?.stepInfos,+ [formStepId]: { status: StepStatus.PENDING },+ },+ },+ }),+ );++ beforeAll(async () => {+ command = getAppProviderByClassName<RecordPendingFormConversationsCommand>(+ 'RecordPendingFormConversationsCommand',+ );+ workspaceOrmManager = getAppProviderByClassName<WorkspaceOrmManager>(+ 'WorkspaceOrmManager',+ );++ const runningWorkflowRuns = (await inWorkspace(() =>+ repository('workflowRun').find({+ where: { status: WorkflowRunStatus.RUNNING },+ select: { id: true, state: true },+ }),+ )) as Pick<WorkflowRunWorkspaceEntity, 'id' | 'state'>[];++ for (const runningWorkflowRun of runningWorkflowRuns) {+ const formStep = runningWorkflowRun.state?.flow?.steps.find(+ (step) =>+ step.type === WorkflowActionType.FORM &&+ runningWorkflowRun.state?.stepInfos[step.id]?.status ===+ StepStatus.PENDING,+ );++ if (formStep !== undefined) {+ workflowRun = runningWorkflowRun;+ formStepId = formStep.id;+ break;+ }+ }+ });++ afterEach(async () => {+ const threadId = await findFormThreadId();+ const seededThreadId = workflowRun.state?.stepInfos[formStepId]?.threadId;++ await inWorkspace(async () => {+ if (threadId !== undefined && threadId !== seededThreadId) {+ await repository('agentChatThread').delete({ id: threadId });+ }++ await repository('workflowRun').update(workflowRun.id, {+ state: workflowRun.state,+ });+ });+ });++ 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: 1790772993322 }),+ ]),+ );+ });++ it('records nothing on a dry run', async () => {+ await forgetFormConversation();++ await runCommand({ dryRun: true });++ expect(await findFormThreadId()).toBeUndefined();+ });++ it('records a pending request_form call named after the step, that the conversation waits on', async () => {+ await forgetFormConversation();++ await runCommand();++ const threadId = await findFormThreadId();++ const thread = await inWorkspace(() =>+ repository('agentChatThread').findOneOrFail({+ where: { id: threadId },+ select: { workflowRunId: true, pendingQuestionMessageId: true },+ }),+ );++ expect(thread.workflowRunId).toBe(workflowRun.id);++ const parts = await inWorkspace(() =>+ repository('agentMessagePart').find({+ where: { messageId: thread.pendingQuestionMessageId },+ select: { toolName: true, toolCallId: true, toolOutput: true },+ }),+ );++ expect(parts).toEqual([+ {+ toolName: 'request_form',+ toolCallId: formStepId,+ toolOutput: expect.objectContaining({+ result: { status: 'pending' },+ }),+ },+ ]);+ });++ it('leaves a form whose conversation is recorded alone', async () => {+ const seededThreadId = workflowRun.state?.stepInfos[formStepId]?.threadId;++ await runCommand();++ expect(seededThreadId).toBeDefined();+ expect(await findFormThreadId()).toBe(seededThreadId);+ });+});diff --git a/packages/twenty-shared/src/ai/constants/request-form-tool-name.const.ts b/packages/twenty-shared/src/ai/constants/request-form-tool-name.const.tsnew file mode 100644index 00000000000..5adc7dd9dbc--- /dev/null+++ b/packages/twenty-shared/src/ai/constants/request-form-tool-name.const.ts@@ -0,0 +1 @@+export const REQUEST_FORM_TOOL_NAME = 'request_form';diff --git a/packages/twenty-shared/src/ai/index.ts b/packages/twenty-shared/src/ai/index.tsindex 5e7204afba2..61df709fc5e 100644--- a/packages/twenty-shared/src/ai/index.ts+++ b/packages/twenty-shared/src/ai/index.ts@@ -31,6 +31,7 @@ export { DEFAULT_AI_AGENT_MODEL_TIER } from './constants/default-ai-agent-model-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 { REQUEST_FORM_TOOL_NAME } from './constants/request-form-tool-name.const';export { ToolCategory } from './constants/tool-category.const';export type { AgentChatSubscriptionEvent } from './types/AgentChatSubscriptionEvent';export type {@@ -58,14 +59,13 @@ export type {} from './types/DataMessagePart';export { isExtendedFileUIPart } from './types/DataMessagePart';export type { EmailApprovalDecision } from './types/EmailApprovalDecision';+export type { EmailApprovalResponse } from './types/EmailApprovalResponse';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';@@ -73,6 +73,14 @@ export type {ProposeEmailToolStatus,ProposeEmailToolResult,} from './types/ProposeEmailToolResult';+export type {+ RequestFormField,+ RequestFormToolInput,+} from './types/RequestFormToolInput';+export type {+ RequestFormToolStatus,+ RequestFormToolResult,+} from './types/RequestFormToolResult';export type { ToolWidgetName, ToolRecordReference } from './types/ToolWidget';export {RECORDS_TOOL_WIDGET_NAME,diff --git a/packages/twenty-shared/src/ai/types/InputAskResponse.ts b/packages/twenty-shared/src/ai/types/EmailApprovalResponse.tssimilarity index 86%rename from packages/twenty-shared/src/ai/types/InputAskResponse.tsrename to packages/twenty-shared/src/ai/types/EmailApprovalResponse.tsindex ecc4e024d96..8699fcacbed 100644--- a/packages/twenty-shared/src/ai/types/InputAskResponse.ts+++ b/packages/twenty-shared/src/ai/types/EmailApprovalResponse.ts@@ -3,7 +3,7 @@ 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 = {+export type EmailApprovalResponse = {decision: EmailApprovalDecision;email?: ProposedEmail;};diff --git a/packages/twenty-shared/src/ai/types/InputAskForm.ts b/packages/twenty-shared/src/ai/types/InputAskForm.tsdeleted file mode 100644index db92c4dc1bf..00000000000--- a/packages/twenty-shared/src/ai/types/InputAskForm.ts+++ /dev/null@@ -1,19 +0,0 @@-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/RequestFormToolInput.ts b/packages/twenty-shared/src/ai/types/RequestFormToolInput.tsnew file mode 100644index 00000000000..ab7423968f1--- /dev/null+++ b/packages/twenty-shared/src/ai/types/RequestFormToolInput.ts@@ -0,0 +1,15 @@+import type z from 'zod';++import { type workflowFormFieldSchema } from '@/workflow/schemas/form-action-settings-schema';++// A workflow form step issues this call with its own fields, so a form step+// and an agent asking for a form are answered the same way. Answers are keyed+// by field name.+export type RequestFormField = Pick<+ z.infer<typeof workflowFormFieldSchema>,+ 'name' | 'label' | 'type' | 'placeholder' | 'settings'+>;++export type RequestFormToolInput = {+ fields: RequestFormField[];+};diff --git a/packages/twenty-shared/src/ai/types/RequestFormToolResult.ts b/packages/twenty-shared/src/ai/types/RequestFormToolResult.tsnew file mode 100644index 00000000000..370aa91ce57--- /dev/null+++ b/packages/twenty-shared/src/ai/types/RequestFormToolResult.ts@@ -0,0 +1,7 @@+export type RequestFormToolStatus = 'pending' | 'answered' | 'skipped';++// Values are keyed by field name.+export type RequestFormToolResult = {+ status: RequestFormToolStatus;+ values?: Record<string, unknown>;+};diff --git a/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap b/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snapindex 2b2c475fd1b..58a3ed0441b 100644--- a/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap+++ b/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap@@ -28,9 +28,6 @@ exports[`STANDARD_OBJECTS universal identifiers should never change without an e"id": {"universalIdentifier": "59b74693-2b88-5eb9-82ef-23b1e75c2b78",},- "inputAsks": {- "universalIdentifier": "0c2444ed-7f90-4984-9f56-a3fe16fa6296",- },"lastStreamError": {"universalIdentifier": "2e389238-ba5c-4951-83d4-b14f94592c5c",},@@ -1521,98 +1518,6 @@ exports[`STANDARD_OBJECTS universal identifiers should never change without an e},},},- "inputAsk": {- "fields": {- "answeredAt": {- "universalIdentifier": "618f303d-123b-480f-9d40-64fcb0db2e01",- },- "assignee": {- "universalIdentifier": "410fabce-972b-40d3-8b11-3c0807ecab90",- },- "createdAt": {- "universalIdentifier": "f0a4adf8-233b-5cfe-855b-25102b196115",- },- "createdBy": {- "universalIdentifier": "1dc3c6fb-1f79-508d-9371-e4b3c43436a5",- },- "deletedAt": {- "universalIdentifier": "32027c67-cdff-5425-873d-b2346e4d9af0",- },- "form": {- "universalIdentifier": "b25c6916-71bc-435e-a547-ecb384083902",- },- "id": {- "universalIdentifier": "3e4b9815-e24e-5548-be38-b82d39e190bd",- },- "name": {- "universalIdentifier": "f8d3b0ed-f134-420a-9194-ca0f96345642",- },- "position": {- "universalIdentifier": "b7e7866d-da15-5753-9bde-43d025a38a86",- },- "response": {- "universalIdentifier": "04906a36-ec59-4d3f-8da9-7ef6696ed326",- },- "searchVector": {- "universalIdentifier": "3eed9577-932b-5c7a-bde5-99ab561f8745",- },- "status": {- "universalIdentifier": "919f0339-ee8e-4197-8b6a-b57bbd31035b",- },- "stepId": {- "universalIdentifier": "334c8abb-6ebe-4e08-a746-0098425ef421",- },- "thread": {- "universalIdentifier": "21ee043a-d3d6-4545-8771-34aca316aeea",- },- "toolCallId": {- "universalIdentifier": "f353edad-fe7e-4efc-ab0d-e21a0ee16262",- },- "updatedAt": {- "universalIdentifier": "168d4eef-366c-59a4-b22a-3b3e2c2fc272",- },- "updatedBy": {- "universalIdentifier": "ca3e2f7a-6c4c-5fbc-b8ed-e3cf6ddabfe7",- },- "workflowRun": {- "universalIdentifier": "cf2d5592-f51c-4dca-a6f2-cb4f7d1fcc80",- },- },- "indexes": {- "assigneeStatusIndex": {- "universalIdentifier": "255cba21-0107-4c31-b497-9c4081114da8",- },- "threadToolCallUniqueIndex": {- "universalIdentifier": "6a0ac44d-84f3-4bfa-8939-ce3d82f0d043",- },- "workflowRunStatusIndex": {- "universalIdentifier": "77615052-0e81-4210-b259-37a9e939bb41",- },- "workflowRunStepUniqueIndex": {- "universalIdentifier": "c6c2c67e-2f2e-4a1e-9c0b-1b3d5e7a9f41",- },- },- "universalIdentifier": "c9069340-a894-4f33-9da3-3b9631d3144c",- "views": {- "allInputAsks": {- "universalIdentifier": "f6b9409d-bb52-5ce9-96a1-0d999d446d1d",- "viewFields": {- "assignee": {- "universalIdentifier": "caf0c3da-7e07-5635-a5e7-06b5b6015ea7",- },- "createdAt": {- "universalIdentifier": "f1f8cced-7d32-5fc7-9ed5-faa9440ce25d",- },- "name": {- "universalIdentifier": "07d46858-2d00-59fd-ba96-45dffced339b",- },- "status": {- "universalIdentifier": "028d2903-6f4d-59fe-9766-6b0f90aaf9b4",- },- },- },- },- },"message": {"fields": {"createdAt": {@@ -3932,9 +3837,6 @@ exports[`STANDARD_OBJECTS universal identifiers should never change without an e"id": {"universalIdentifier": "e8f6e894-4003-5cb1-a1c1-7ed5b3e4200c",},- "inputAsks": {- "universalIdentifier": "f3b2f310-9aa4-40da-82bb-3388d26e7cde",- },"name": {"universalIdentifier": "20202020-b840-4253-aef9-4e5013694587",},@@ -4220,9 +4122,6 @@ exports[`STANDARD_OBJECTS universal identifiers should never change without an e"id": {"universalIdentifier": "d77dff76-dcfd-52a3-b352-832898b28b9d",},- "inputAsks": {- "universalIdentifier": "552a26c5-21fd-4e3a-ad0d-2f561c96b7d4",- },"jobTitle": {"universalIdentifier": "20202020-4dd4-4619-826e-08f6c06b374d",},diff --git a/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts b/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.tsindex 76f489c46b8..9b566e650e5 100644--- a/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts+++ b/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts@@ -84,7 +84,6 @@ export const STANDARD_OBJECT_FIELDS = {recordTargets: {universalIdentifier: '5b37eceb-2992-4d27-9897-14af3e3ce9b2',},- inputAsks: { universalIdentifier: '0c2444ed-7f90-4984-9f56-a3fe16fa6296' },},agentChatThreadTarget: {...buildStandardObjectBaseFields(@@ -1500,9 +1499,6 @@ export const STANDARD_OBJECT_FIELDS = {STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.timelineActivity,}),},- inputAsks: {- universalIdentifier: 'f3b2f310-9aa4-40da-82bb-3388d26e7cde',- },},workflowVersion: {...buildStandardObjectSystemFields(@@ -1605,27 +1601,5 @@ export const STANDARD_OBJECT_FIELDS = {numberFormat: {universalIdentifier: '20202020-7f40-4e7f-b126-11c0eda6b141',},- inputAsks: {- universalIdentifier: '552a26c5-21fd-4e3a-ad0d-2f561c96b7d4',- },- },- inputAsk: {- ...buildStandardObjectSystemFields(- STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.inputAsk,- ),- name: { universalIdentifier: 'f8d3b0ed-f134-420a-9194-ca0f96345642' },- status: { universalIdentifier: '919f0339-ee8e-4197-8b6a-b57bbd31035b' },- form: { universalIdentifier: 'b25c6916-71bc-435e-a547-ecb384083902' },- response: { universalIdentifier: '04906a36-ec59-4d3f-8da9-7ef6696ed326' },- assignee: { universalIdentifier: '410fabce-972b-40d3-8b11-3c0807ecab90' },- answeredAt: { universalIdentifier: '618f303d-123b-480f-9d40-64fcb0db2e01' },- workflowRun: {- universalIdentifier: 'cf2d5592-f51c-4dca-a6f2-cb4f7d1fcc80',- },- stepId: { universalIdentifier: '334c8abb-6ebe-4e08-a746-0098425ef421' },- toolCallId: {- universalIdentifier: 'f353edad-fe7e-4efc-ab0d-e21a0ee16262',- },- thread: { universalIdentifier: '21ee043a-d3d6-4545-8771-34aca316aeea' },},} satisfies Record<string, Record<string, { universalIdentifier: string }>>;diff --git a/packages/twenty-shared/src/metadata/constants/standard-object-universal-identifiers.constant.ts b/packages/twenty-shared/src/metadata/constants/standard-object-universal-identifiers.constant.tsindex 676d2b69c47..f274f7aca05 100644--- a/packages/twenty-shared/src/metadata/constants/standard-object-universal-identifiers.constant.ts+++ b/packages/twenty-shared/src/metadata/constants/standard-object-universal-identifiers.constant.ts@@ -46,7 +46,6 @@ export const STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS = {messageParticipant: '20202020-a433-4456-aa2d-fd9cb26b774a',messageThread: '20202020-849a-4c3e-84f5-a25a7d802271',messageThreadTarget: '378ad1b0-592d-4084-80ee-86fef44725b9',- inputAsk: 'c9069340-a894-4f33-9da3-3b9631d3144c',} as const;export type StandardObjectWithUniversalIdentifierName =diff --git a/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts b/packages/twenty-shared/src/metadata/constants/standard-object.constant.tsindex aaf462804c8..c5beca88f85 100644--- a/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts+++ b/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts@@ -1548,32 +1548,6 @@ export const STANDARD_OBJECTS = {},},},- inputAsk: {- universalIdentifier: STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.inputAsk,- fields: STANDARD_OBJECT_FIELDS.inputAsk,- indexes: {- assigneeStatusIndex: {- universalIdentifier: '255cba21-0107-4c31-b497-9c4081114da8',- },- workflowRunStepUniqueIndex: {- universalIdentifier: 'c6c2c67e-2f2e-4a1e-9c0b-1b3d5e7a9f41',- },- workflowRunStatusIndex: {- universalIdentifier: '77615052-0e81-4210-b259-37a9e939bb41',- },- threadToolCallUniqueIndex: {- universalIdentifier: '6a0ac44d-84f3-4bfa-8939-ce3d82f0d043',- },- },- views: {- allInputAsks: buildStandardObjectIndexView({- objectUniversalIdentifier:- STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.inputAsk,- fields: STANDARD_OBJECT_FIELDS.inputAsk,- viewFieldNames: ['name', 'status', 'assignee', 'createdAt'],- }),- },- },} as const satisfies Record<string,{diff --git a/packages/twenty-shared/src/types/CoreObjectNameSingular.ts b/packages/twenty-shared/src/types/CoreObjectNameSingular.tsindex 595057a64a4..65e656c1ed1 100644--- a/packages/twenty-shared/src/types/CoreObjectNameSingular.ts+++ b/packages/twenty-shared/src/types/CoreObjectNameSingular.ts@@ -13,7 +13,6 @@ export enum CoreObjectNameSingular {Comment = 'comment',Company = 'company',Dashboard = 'dashboard',- InputAsk = 'inputAsk',TimelineActivity = 'timelineActivity',Message = 'message',MessageCampaign = 'messageCampaign',diff --git a/packages/twenty-shared/src/workflow/index.ts b/packages/twenty-shared/src/workflow/index.tsindex c7296b369b7..0c985fd8f02 100644--- a/packages/twenty-shared/src/workflow/index.ts+++ b/packages/twenty-shared/src/workflow/index.ts@@ -62,7 +62,10 @@ export { workflowFilterActionSettingsSchema } from './schemas/filter-action-settexport { workflowFindRecordsActionSchema } from './schemas/find-records-action-schema';export { workflowFindRecordsActionSettingsSchema } from './schemas/find-records-action-settings-schema';export { workflowFormActionSchema } from './schemas/form-action-schema';-export { workflowFormActionSettingsSchema } from './schemas/form-action-settings-schema';+export {+ workflowFormFieldSchema,+ workflowFormActionSettingsSchema,+} from './schemas/form-action-settings-schema';export { workflowHttpRequestActionSchema } from './schemas/http-request-action-schema';export { workflowHttpRequestActionSettingsSchema } from './schemas/http-request-action-settings-schema';export { workflowIfElseActionSchema } from './schemas/if-else-action-schema';diff --git a/packages/twenty-shared/src/workflow/schemas/form-action-settings-schema.ts b/packages/twenty-shared/src/workflow/schemas/form-action-settings-schema.tsindex a529afb4e72..b6d0660a15b 100644--- a/packages/twenty-shared/src/workflow/schemas/form-action-settings-schema.ts+++ b/packages/twenty-shared/src/workflow/schemas/form-action-settings-schema.ts@@ -2,24 +2,24 @@ import { z } from 'zod';import { FieldMetadataType } from '../../types/FieldMetadataType';import { baseWorkflowActionSettingsSchema } from './base-workflow-action-settings-schema';+export const workflowFormFieldSchema = z.object({+ id: z.string(),+ name: z.string(),+ label: z.string(),+ type: z.union([+ z.literal(FieldMetadataType.TEXT),+ z.literal(FieldMetadataType.NUMBER),+ z.literal(FieldMetadataType.DATE),+ z.literal(FieldMetadataType.SELECT),+ z.literal(FieldMetadataType.MULTI_SELECT),+ z.literal('RECORD'),+ ]),+ placeholder: z.string().optional(),+ settings: z.record(z.string(), z.any()).optional(),+ value: z.any().optional(),+});+export const workflowFormActionSettingsSchema =baseWorkflowActionSettingsSchema.extend({- input: z.array(- z.object({- id: z.string(),- name: z.string(),- label: z.string(),- type: z.union([- z.literal(FieldMetadataType.TEXT),- z.literal(FieldMetadataType.NUMBER),- z.literal(FieldMetadataType.DATE),- z.literal(FieldMetadataType.SELECT),- z.literal(FieldMetadataType.MULTI_SELECT),- z.literal('RECORD'),- ]),- placeholder: z.string().optional(),- settings: z.record(z.string(), z.any()).optional(),- value: z.any().optional(),- }),- ),+ input: z.array(workflowFormFieldSchema),});