The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(workflow): a form step waits on its run, not in a conversation (#27250)
Félix Malfait85ac396369db
diff --git a/packages/twenty-docs/user-guide/workflows/capabilities/workflow-actions.mdx b/packages/twenty-docs/user-guide/workflows/capabilities/workflow-actions.mdxindex 70d1683f12c..3e5062f0870 100644--- a/packages/twenty-docs/user-guide/workflows/capabilities/workflow-actions.mdx+++ b/packages/twenty-docs/user-guide/workflows/capabilities/workflow-actions.mdx@@ -220,9 +220,9 @@ Creates an event on a connected calendar.**Output**: The created event data is available for use in subsequent steps.### Form-Prompts a form during workflow execution to collect user input. The responses can then be used in subsequent steps to create records, send emails, or execute any other action based on the input.+Opens a form for the person who launches the workflow, to collect input on the spot. The responses can then be used in subsequent steps to create records, send emails, or execute any other action based on the input.<Warning>-**Forms are designed for manual triggers only**. For workflows with other triggers (Record Created, Updated, etc.), forms are only accessible via the workflow run interface, which is not the expected user experience. A notification center will be released in 2026 to properly support forms in automated workflows.+**Forms are designed for manual triggers only**. A form is filled in right away by the person running the workflow and does not reach anyone's inbox. For workflows with other triggers (Record Created, Updated, etc.), forms are only accessible via the workflow run interface. To ask someone for an answer or an approval in their inbox, use the Send to Inbox step instead.</Warning>**Configuration**:- Configure the fields that users will be asked to fill. For each field, choosediff --git a/packages/twenty-front/src/generated/graphql.ts b/packages/twenty-front/src/generated/graphql.tsindex 54bbe1fd603..9f0fe6dbc7d 100644--- a/packages/twenty-front/src/generated/graphql.ts+++ b/packages/twenty-front/src/generated/graphql.ts@@ -461,6 +461,7 @@ export type Mutation = {runCoreWorkflowVersion: RunWorkflowVersion;runWorkflowVersion: RunWorkflowVersion;stopWorkflowRun: WorkflowRun;+ submitFormStep: Scalars['Boolean']['output'];testHttpRequest: TestHttpRequest;updateCoreWorkflow?: Maybe<CoreWorkflowDto>;updateCoreWorkflowVersionPositions: Scalars['Boolean']['output'];@@ -620,6 +621,11 @@ export type MutationStopWorkflowRunArgs = {};+export type MutationSubmitFormStepArgs = {+ input: SubmitFormStepInput;+};++export type MutationTestHttpRequestArgs = {input: TestHttpRequestInput;};@@ -890,6 +896,15 @@ export type SearchResultPageInfo = {hasNextPage: Scalars['Boolean']['output'];};+export type SubmitFormStepInput = {+ /** Form values keyed by field name */+ response: Scalars['JSON']['input'];+ /** Form step ID */+ stepId: Scalars['UUID']['input'];+ /** Workflow run ID */+ workflowRunId: Scalars['UUID']['input'];+};+export type TestHttpRequest = {__typename?: 'TestHttpRequest';/** Error information */@@ -1494,6 +1509,13 @@ export type StopWorkflowRunMutationVariables = Exact<{export type StopWorkflowRunMutation = { __typename?: 'Mutation', stopWorkflowRun: { __typename: 'WorkflowRun', id: any, status: WorkflowRunStatusEnum } };+export type SubmitFormStepMutationVariables = Exact<{+ input: SubmitFormStepInput;+}>;+++export type SubmitFormStepMutation = { __typename?: 'Mutation', submitFormStep: boolean };+export type UpdateWorkflowRunStepMutationVariables = Exact<{input: UpdateWorkflowRunStepInput;}>;@@ -1593,6 +1615,7 @@ export const DuplicateWorkflowVersionStepDocument = {"kind":"Document","definitiexport const RetryWorkflowRunDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RetryWorkflowRun"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workflowRunId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"retryWorkflowRun"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workflowRunId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workflowRunId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"__typename"}}]}}]}}]} as unknown as DocumentNode<RetryWorkflowRunMutation, RetryWorkflowRunMutationVariables>;export const RunWorkflowVersionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RunWorkflowVersion"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"RunWorkflowVersionInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"runWorkflowVersion"},"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":"workflowRunId"}}]}}]}}]} as unknown as DocumentNode<RunWorkflowVersionMutation, RunWorkflowVersionMutationVariables>;export const StopWorkflowRunDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"StopWorkflowRun"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workflowRunId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"stopWorkflowRun"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workflowRunId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workflowRunId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"__typename"}}]}}]}}]} as unknown as DocumentNode<StopWorkflowRunMutation, StopWorkflowRunMutationVariables>;+export const SubmitFormStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SubmitFormStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SubmitFormStepInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"submitFormStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]} as unknown as DocumentNode<SubmitFormStepMutation, SubmitFormStepMutationVariables>;export const UpdateWorkflowRunStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkflowRunStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateWorkflowRunStepInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkflowRunStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"settings"}},{"kind":"Field","name":{"kind":"Name","value":"valid"}},{"kind":"Field","name":{"kind":"Name","value":"nextStepIds"}},{"kind":"Field","name":{"kind":"Name","value":"position"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"x"}},{"kind":"Field","name":{"kind":"Name","value":"y"}}]}}]}}]}}]} as unknown as DocumentNode<UpdateWorkflowRunStepMutation, UpdateWorkflowRunStepMutationVariables>;export const UpdateWorkflowVersionStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkflowVersionStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateWorkflowVersionStepInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkflowVersionStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"settings"}},{"kind":"Field","name":{"kind":"Name","value":"valid"}},{"kind":"Field","name":{"kind":"Name","value":"nextStepIds"}},{"kind":"Field","name":{"kind":"Name","value":"position"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"x"}},{"kind":"Field","name":{"kind":"Name","value":"y"}}]}}]}}]}}]} as unknown as DocumentNode<UpdateWorkflowVersionStepMutation, UpdateWorkflowVersionStepMutationVariables>;export const UpdateWorkflowVersionTriggerDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkflowVersionTrigger"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateWorkflowVersionTriggerInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkflowVersionTrigger"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"trigger"}}]}}]}}]} as unknown as DocumentNode<UpdateWorkflowVersionTriggerMutation, UpdateWorkflowVersionTriggerMutationVariables>;diff --git a/packages/twenty-front/src/modules/workflow/graphql/mutations/submitFormStep.ts b/packages/twenty-front/src/modules/workflow/graphql/mutations/submitFormStep.tsnew file mode 100644index 00000000000..a8ad41b7718--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/graphql/mutations/submitFormStep.ts@@ -0,0 +1,7 @@+import { gql } from '@apollo/client';++export const SUBMIT_FORM_STEP = gql`+ mutation SubmitFormStep($input: SubmitFormStepInput!) {+ submitFormStep(input: $input)+ }+`;diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormBuilder.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormBuilder.tsxindex d3cbe7a6fe7..5c5e71af63f 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormBuilder.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormBuilder.tsx@@ -244,8 +244,8 @@ export const WorkflowEditActionFormBuilder = ({<Calloutvariant={'warning'}Icon={IconAlertTriangle}- title={t`This form will appear in workflow runs.`}- description={t`Because this workflow is not using a manual trigger, the form will not open on top of the interface. To fill it, open the corresponding workflow run and complete the form there.`}+ title={t`Forms are meant for manual triggers`}+ description={t`A form opens for the person who launches the workflow and is filled in on the spot. With this trigger, it only shows in the workflow run. To ask someone for an answer or an approval in their inbox, use a Send to Inbox step instead.`}isClosablecloseLabel={t`Close`}onClose={() => setIsCalloutVisible(false)}@@ -267,7 +267,7 @@ export const WorkflowEditActionFormBuilder = ({variant={'neutral'}isClosable={false}title={t`Add inputs to your form`}- description={t`Click on "Add Field" below to add the first input to your form. The form will pop up on the user's screen when the workflow is launched from a manual trigger. For other types of triggers, it will be displayed in the Workflow run record page.`}+ description={t`Click on "Add Field" below to add the first input to your form. The form pops up for the person who launches the workflow manually. For workflows with other triggers, it is filled in from the workflow run.`}/></StyledNotClosableCalloutContainer>)}diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormStepSubmitButton.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormStepSubmitButton.tsxindex e3036fdeda2..92f09185811 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormStepSubmitButton.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormStepSubmitButton.tsx@@ -1,6 +1,6 @@import { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';import { WorkflowStepCmdEnterButton } from '@/workflow/workflow-steps/components/WorkflowStepCmdEnterButton';-import { useAnswerFormStep } from '@/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStep';+import { useSubmitFormStep } from '@/workflow/workflow-steps/workflow-actions/form-action/hooks/useSubmitFormStep';import { useLingui } from '@lingui/react/macro';import { useState } from 'react';import { useToast } from 'twenty-ui/components';@@ -22,7 +22,7 @@ export const WorkflowFormStepSubmitButton = ({}: WorkflowFormStepSubmitButtonProps) => {const { t } = useLingui();const { enqueueToast } = useToast();- const { answerFormStep } = useAnswerFormStep({+ const { submitFormStep } = useSubmitFormStep({workflowRunId,stepId,});@@ -36,18 +36,10 @@ export const WorkflowFormStepSubmitButton = ({setIsSubmitting(true);try {- const isSubmitted = await answerFormStep(await getResponse());+ await submitFormStep(await getResponse());+ onSubmitted();- if (isSubmitted) {- onSubmitted();-- return;- }-- enqueueToast({- variant: 'error',- children: t`This form no longer waits for an answer`,- });+ return;} catch (error) {enqueueToast(getToastOptionsFromError({ error }));}diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/__stories__/WorkflowFormStepSubmitButton.stories.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/__stories__/WorkflowFormStepSubmitButton.stories.tsxindex 84169a9f9e3..ba2ec522065 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/__stories__/WorkflowFormStepSubmitButton.stories.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/__stories__/WorkflowFormStepSubmitButton.stories.tsx@@ -18,7 +18,6 @@ import { mockedApolloClient } from '~/testing/mockedApolloClient';const WORKFLOW_RUN_ID = oneSucceededWorkflowRunQueryResult.workflowRun.id;const STEP_ID = '212a171a-f887-4213-8892-e39c2a3ecc30';-const THREAD_ID = 'a19e36a1-e3bb-4fa0-8317-79c7e938849e';const FormSubmission = () => {const [isSubmitted, setIsSubmitted] = useState(false);@@ -46,7 +45,13 @@ const FormSubmission = () => {);};-const createHandlers = ({ errorCode }: { errorCode?: string } = {}) => [+const createHandlers = ({+ errorCode,+ userFriendlyMessage = 'Unable to submit form',+}: {+ errorCode?: string;+ userFriendlyMessage?: string;+} = {}) => [graphql.query('FindOneWorkflowRun', () =>HttpResponse.json({data: {@@ -62,36 +67,24 @@ const createHandlers = ({ errorCode }: { errorCode?: string } = {}) => [},state: {...oneSucceededWorkflowRunQueryResult.workflowRun.state,- stepInfos: {- [STEP_ID]: { status: 'PENDING', threadId: THREAD_ID },- },+ stepInfos: { [STEP_ID]: { status: 'PENDING' } },},},},}),),- graphql.mutation('AnswerToolCall', () =>+ graphql.mutation('SubmitFormStep', () =>HttpResponse.json(errorCode? {errors: [{- message: 'Unable to submit form',- extensions: {- code: errorCode,- userFriendlyMessage: 'Unable to submit form',- },+ message: userFriendlyMessage,+ extensions: { code: errorCode, userFriendlyMessage },},],}- : {- data: {- answerToolCall: {- __typename: 'AnswerToolCallResult',- streamId: null,- },- },- },+ : { data: { submitFormStep: true } },),),...graphqlMocks.handlers,@@ -132,7 +125,12 @@ export const Submitted: Story = {export const NoLongerPending: Story = {parameters: {- msw: { handlers: createHandlers({ errorCode: 'TOOL_CALL_NOT_PENDING' }) },+ msw: {+ handlers: createHandlers({+ errorCode: 'BAD_USER_INPUT',+ userFriendlyMessage: 'This form no longer waits for an answer.',+ }),+ },},play: async ({ canvasElement }) => {const canvas = within(canvasElement);@@ -142,7 +140,7 @@ export const NoLongerPending: Story = {);expect(await within(document.body).findByText(- 'This form no longer waits for an answer',+ 'This form no longer waits for an answer.',),).toBeVisible();expect(canvas.queryByText('Form submitted')).not.toBeInTheDocument();@@ -153,7 +151,7 @@ export const NoLongerPending: Story = {export const SubmissionError: Story = {parameters: {msw: {- handlers: createHandlers({ errorCode: 'TOOL_CALL_RESOLUTION_FORBIDDEN' }),+ handlers: createHandlers({ errorCode: 'FORBIDDEN' }),},},play: async ({ canvasElement }) => {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.tsdeleted file mode 100644index 828612272f4..00000000000--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStep.ts+++ /dev/null@@ -1,69 +0,0 @@-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',- });-- 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/useSubmitFormStep.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useSubmitFormStep.tsnew file mode 100644index 00000000000..788beabcda6--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useSubmitFormStep.ts@@ -0,0 +1,59 @@+import { useMutation } from '@apollo/client/react';+import { CoreObjectNameSingular } from 'twenty-shared/types';++import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';+import { useFindOneRecordQuery } from '@/object-record/hooks/useFindOneRecordQuery';+import { SUBMIT_FORM_STEP } from '@/workflow/graphql/mutations/submitFormStep';+import {+ type SubmitFormStepMutation,+ type SubmitFormStepMutationVariables,+} from '~/generated/graphql';++export const useSubmitFormStep = ({+ workflowRunId,+ stepId,+}: {+ workflowRunId: string;+ stepId: string;+}) => {+ const apolloCoreClient = useApolloCoreClient();+ const [mutate] = useMutation<+ SubmitFormStepMutation,+ SubmitFormStepMutationVariables+ >(SUBMIT_FORM_STEP, { client: apolloCoreClient });++ const { findOneRecordQuery: findOneWorkflowRunQuery } = useFindOneRecordQuery(+ {+ objectNameSingular: CoreObjectNameSingular.WorkflowRun,+ recordGqlFields: {+ id: true,+ name: true,+ status: true,+ startedAt: true,+ endedAt: true,+ },+ },+ );++ // the refresh only updates the cache, so its failure must not change the submission's outcome+ const refetchWorkflowRun = () =>+ apolloCoreClient+ .query({+ query: findOneWorkflowRunQuery,+ variables: { objectRecordId: workflowRunId },+ fetchPolicy: 'network-only',+ })+ .catch(() => undefined);++ const submitFormStep = async (response: Record<string, unknown>) => {+ try {+ await mutate({+ variables: { input: { workflowRunId, stepId, response } },+ });+ } finally {+ await refetchWorkflowRun();+ }+ };++ return { submitFormStep };+};diff --git a/packages/twenty-server/src/engine/core-modules/workflow/dtos/submit-form-step.input.ts b/packages/twenty-server/src/engine/core-modules/workflow/dtos/submit-form-step.input.tsnew file mode 100644index 00000000000..8d9c272cb0a--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workflow/dtos/submit-form-step.input.ts@@ -0,0 +1,26 @@+import { Field, InputType } from '@nestjs/graphql';++import graphqlTypeJson from 'graphql-type-json';++import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';++@InputType()+export class SubmitFormStepInput {+ @Field(() => UUIDScalarType, {+ description: 'Workflow run ID',+ nullable: false,+ })+ workflowRunId: string;++ @Field(() => UUIDScalarType, {+ description: 'Form step ID',+ nullable: false,+ })+ stepId: string;++ @Field(() => graphqlTypeJson, {+ description: 'Form values keyed by field name',+ nullable: false,+ })+ response: Record<string, unknown>;+}diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.tsindex 901a64065c3..28f7191a6f9 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.ts@@ -3,6 +3,7 @@ import { Args, Mutation, Query } from '@nestjs/graphql';import { msg } from '@lingui/core/macro';import { PermissionFlagType } from 'twenty-shared/constants';+import { isPlainObject } from 'twenty-shared/utils';import { CoreResolver } from 'src/engine/api/graphql/graphql-config/decorators/core-resolver.decorator';import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';@@ -14,6 +15,7 @@ import { DeleteWorkflowVersionStepInput } from 'src/engine/core-modules/workflowimport { DuplicateWorkflowVersionStepInput } from 'src/engine/core-modules/workflow/dtos/duplicate-workflow-version-step.input';import { TestHttpRequestInput } from 'src/engine/core-modules/workflow/dtos/test-http-request.input';import { TestHttpRequestDTO } from 'src/engine/core-modules/workflow/dtos/test-http-request.dto';+import { SubmitFormStepInput } from 'src/engine/core-modules/workflow/dtos/submit-form-step.input';import { UpdateWorkflowRunStepInput } from 'src/engine/core-modules/workflow/dtos/update-workflow-run-step.input';import { UpdateWorkflowVersionStepInput } from 'src/engine/core-modules/workflow/dtos/update-workflow-version-step.input';import { UpdateWorkflowVersionTriggerInput } from 'src/engine/core-modules/workflow/dtos/update-workflow-version-trigger.input';@@ -38,6 +40,7 @@ import {import { WorkflowVersionStepWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.workspace-service';import { canUpdateWorkflowRunStep } from 'src/modules/workflow/workflow-runner/utils/can-update-workflow-run-step.util';import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';+import { WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service';import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';@CoreResolver()@@ -67,6 +70,7 @@ export class WorkflowVersionStepResolver {constructor(private readonly workflowVersionStepWorkspaceService: WorkflowVersionStepWorkspaceService,private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,+ private readonly workflowRunnerWorkspaceService: WorkflowRunnerWorkspaceService,private readonly httpTool: HttpTool,private readonly connectedAccountMetadataService: ConnectedAccountMetadataService,private readonly coreWorkflowAccessService: CoreWorkflowAccessService,@@ -219,6 +223,39 @@ export class WorkflowVersionStepResolver {return step;}+ @Mutation(() => Boolean)+ async submitFormStep(+ @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @Args('input') { workflowRunId, stepId, response }: SubmitFormStepInput,+ ): Promise<boolean> {+ if (!isPlainObject(response)) {+ throw new WorkflowVersionStepException(+ 'A form response must be an object',+ WorkflowVersionStepExceptionCode.INVALID_REQUEST,+ );+ }++ if (+ !(await this.workflowRunWorkspaceService.isWorkflowRunReadableByRequester(+ workflowRunId,+ ))+ ) {+ throw new WorkflowVersionStepException(+ 'Workflow run not found',+ WorkflowVersionStepExceptionCode.NOT_FOUND,+ );+ }++ await this.workflowRunnerWorkspaceService.submitFormStep({+ workspaceId,+ workflowRunId,+ stepId,+ response,+ });++ return true;+ }+@Mutation(() => WorkflowVersionStepChangesDTO)async duplicateWorkflowVersionStep(@AuthUserWorkspaceId({ allowUndefined: true })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.tsindex cf3c1f5559d..1f0b7b95be3 100644--- 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.ts@@ -17,7 +17,7 @@ const requestFormFieldSchema = workflowFormFieldSchema.pick({settings: true,});-// form steps issue this call with every field, so recorded calls skip the agent's limits+// form steps used to issue this call with every field, so recorded calls skip the agent's limitsconst requestFormCallSchema = z.object({fields: z.array(requestFormFieldSchema),});@@ -39,7 +39,6 @@ export const requestFormInputSchema = z.object({),});-// A workflow form step writes the same output when it issues this call.export const buildRequestFormPendingOutput = (): {success: true;message: string;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.tsindex a7b976998be..11c05b1efd4 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts@@ -30,13 +30,8 @@ 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 { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';-import {- WorkflowRunStatus,- type WorkflowRunWorkspaceEntity,-} from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';+import { WorkflowRunStatus } 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';@@ -74,7 +69,6 @@ export class ToolCallAnswerService {private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,private readonly permissionsService: PermissionsService,private readonly turnPreflightService: AgentChatTurnPreflightService,- private readonly workspaceOrmManager: WorkspaceOrmManager,private readonly agentActorContextService: AgentActorContextService,private readonly toolRegistryService: ToolRegistryService,) {}@@ -343,7 +337,6 @@ export class ToolCallAnswerService {workflowRunId,step,threadId,- response: validation.output,toolResult,});}@@ -471,24 +464,11 @@ export class ToolCallAnswerService {workspaceId,});- let workflowRun: Pick<WorkflowRunWorkspaceEntity, 'id'> | null = null;-- try {- workflowRun = await this.workspaceOrmManager.executeInWorkspaceContext(- () =>- this.workspaceOrmManager- .getRepositoryWithContextPermissions<WorkflowRunWorkspaceEntity>(- 'workflowRun',- )- .findOne({ where: { id: workflowRunId }, select: { id: true } }),- );- } catch (error) {- if (!(error instanceof PermissionsException)) {- throw error;- }- }-- if (!isDefined(workflowRun)) {+ if (+ !(await this.workflowRunWorkspaceService.isWorkflowRunReadableByRequester(+ workflowRunId,+ ))+ ) {throw new AiException('The tool call to answer could not be found',AiExceptionCode.TOOL_CALL_NOT_FOUND,diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.tsindex 741ad8ba16f..d74ce39f010 100644--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts@@ -1,12 +1,7 @@import { Injectable } from '@nestjs/common';-import { type AskQuestionItem, REQUEST_FORM_TOOL_NAME } from 'twenty-shared/ai';-import {- type ActorMetadata,- FieldActorSource,- FieldMetadataType,-} from 'twenty-shared/types';-import { isDefined } from 'twenty-shared/utils';+import { type AskQuestionItem } from 'twenty-shared/ai';+import { type ActorMetadata, FieldActorSource } from 'twenty-shared/types';import { StepStatus, WorkflowActionType } from 'twenty-shared/workflow';import { v5 } from 'uuid';@@ -15,11 +10,6 @@ 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';@@ -36,10 +26,7 @@ import {type WorkflowWorkspaceEntity,} from 'src/modules/workflow/common/standard-objects/workflow.workspace-entity';import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';-import {- type WorkflowAction,- type WorkflowFormAction,-} from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';+import { 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 {type WorkflowManualTrigger,@@ -64,10 +51,6 @@ const INITIATORS = {workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,name: 'Tim Apple',},- JONY: {- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,- name: 'Jony Ive',- },PHIL: {workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.PHIL,name: 'Phil Schiler',@@ -162,29 +145,6 @@ const AGENT_WORKFLOWS_TO_SEED: AgentWorkflowToSeed[] = [},];-const DISCOUNT_RUNS_TO_SEED: {- suffix: string;- initiator: Initiator;- endStatus?: WorkflowRunStatus.COMPLETED | WorkflowRunStatus.STOPPED;- response?: Record<string, unknown>;-}[] = [- {- suffix: 'Answered',- initiator: 'TIM',- endStatus: WorkflowRunStatus.COMPLETED,- response: {- discount: 15,- justification: 'Three-year commitment signed by Airbnb procurement.',- },- },- {- suffix: 'Stopped',- initiator: 'PHIL',- endStatus: WorkflowRunStatus.STOPPED,- },- { suffix: 'Pending', initiator: 'JONY' },-];-const ERROR_HANDLING_OPTIONS = {retryOnFailure: { value: 0 },continueOnFailure: { value: false },@@ -203,10 +163,6 @@ type SeededWorkflow = {@Injectable()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,@@ -298,93 +254,6 @@ export class DevSeederWorkflowPendingInputWorkspaceService {}),});}-- const formStep: WorkflowFormAction = {- id: seedId('formStep', workspaceId),- name: 'Approve discount',- type: WorkflowActionType.FORM,- valid: true,- settings: {- input: [- {- id: seedId('formField:discount', workspaceId),- name: 'discount',- label: 'Approved discount (%)',- type: FieldMetadataType.NUMBER,- placeholder: '10',- },- {- id: seedId('formField:justification', workspaceId),- name: 'justification',- label: 'Justification',- type: FieldMetadataType.TEXT,- placeholder: 'Why this discount is worth it',- },- ],- outputSchema: {},- errorHandlingOptions: ERROR_HANDLING_OPTIONS,- },- nextStepIds: [],- };-- const discountWorkflow = await this.insertWorkflow({- workspaceId,- applicationId,- key: 'approveDiscount',- name: 'Approve discount',- position: 5,- icon: 'IconDiscount',- step: formStep,- });-- for (const discountRun of DISCOUNT_RUNS_TO_SEED) {- const workflowRunId = seedId(- `workflowRun:discount${discountRun.suffix}`,- workspaceId,- );-- await this.seedPausedRun({- workspaceId,- workflowRunId,- workflow: discountWorkflow,- initiator: discountRun.initiator,- 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,- },- workflowRunId,- workspaceId,- });- }-- if (isDefined(discountRun.endStatus)) {- await this.workflowRunWorkspaceService.endWorkflowRun({- workflowRunId,- workspaceId,- status: discountRun.endStatus,- });- }- }}private async seedPausedRun({@@ -434,45 +303,6 @@ export class DevSeederWorkflowPendingInputWorkspaceService {});}- 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/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 f7d84dd8267..bc0f8b1dfb7 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts@@ -1,15 +1,9 @@import { Injectable, Logger } from '@nestjs/common';-import {- type ExtendedUIMessagePart,- REQUEST_FORM_TOOL_NAME,- type RequestFormToolInput,-} from 'twenty-shared/ai';import { isDefined } from 'twenty-shared/utils';import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';-import { buildRequestFormPendingOutput } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/request-form.pausing-tool';import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';@@ -94,50 +88,6 @@ export class WorkflowAgentConversationWorkspaceService {return { threadId, isAwaitingAnswer };}- // A form step is answered like any call that waits on a person- async recordFormRequest({- workspaceId,- workflowRunId,- stepId,- title,- fields,- }: {- workspaceId: string;- workflowRunId: string;- stepId: string;- title: string;- fields: RequestFormToolInput['fields'];- }): Promise<void> {- const { threadId, turnId } = await this.openConversation({- workspaceId,- workflowRunId,- stepId,- title,- agentId: null,- });-- await this.conversationWriterService.insertMessage({- workspaceId,- threadId,- turnId,- role: AgentMessageRole.ASSISTANT,- agentId: null,- senderUserWorkspaceId: null,- isAwaitingAnswer: true,- parts: [- {- type: `tool-${REQUEST_FORM_TOOL_NAME}`,- toolCallId: stepId,- state: 'output-available',- input: { fields },- output: buildRequestFormPendingOutput(),- } as ExtendedUIMessagePart,- ],- });-- await this.recordWaitingActivity({ workspaceId, threadId, text: title });- }-// The answer is already the last message, so only the agent's reply is addedasync recordContinuation({workspaceId,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 6a250bcc57e..1600d235b9c 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form-action.module.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form-action.module.ts@@ -1,10 +1,8 @@import { Module } from '@nestjs/common';-import { 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 45bffd5e51c..6c1ffb4fbd4 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,19 +9,13 @@ 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,@@ -35,14 +29,6 @@ export class FormWorkflowAction implements WorkflowAction {);}- 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-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.tsindex 69c0b28b377..4093d6131b0 100644--- 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.ts@@ -1,4 +1,4 @@-import { StepStatus } from 'twenty-shared/workflow';+import { StepStatus, WorkflowActionType } from 'twenty-shared/workflow';import { IsNull } from 'typeorm';import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';@@ -63,12 +63,16 @@ describe('WorkflowRunWorkspaceService conversations', () => {},});- const step = { id: 'step-id', name: 'Ask' };+ const step = {+ id: 'step-id',+ name: 'Ask',+ type: WorkflowActionType.AI_AGENT,+ };const workflowRun: {id: string;status: WorkflowRunStatus;state: {- flow: { steps: { id: string; name: string }[] };+ flow: { steps: { id: string; name: string; type: string }[] };stepInfos: Record<string, Record<string, unknown>>;};} = {@@ -111,7 +115,11 @@ describe('WorkflowRunWorkspaceService conversations', () => {it('finds the step a call names among steps sharing one inbox conversation', async () => {const { service, workflowRun } = buildService();- const approvalStep = { id: 'second-step-id', name: 'Approve' };+ const approvalStep = {+ id: 'second-step-id',+ name: 'Approve',+ type: WorkflowActionType.SEND_CHAT_MESSAGE,+ };workflowRun.state = {flow: { steps: [...workflowRun.state.flow.steps, approvalStep] },@@ -137,6 +145,16 @@ describe('WorkflowRunWorkspaceService conversations', () => {expect(await findStep(service)).toEqual(approvalStep);});+ it('finds nothing for a form step, which is submitted from its run', async () => {+ const { service, workflowRun } = buildService();++ workflowRun.state.flow.steps = [+ { id: 'step-id', name: 'Form', type: WorkflowActionType.FORM },+ ];++ expect(await findStep(service)).toBeNull();+ });+it.each([['the run is no longer running', { status: WorkflowRunStatus.STOPPED }],[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 1cc7de30ec7..4073ce79a1b 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@@ -11,6 +11,7 @@ import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service'import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';import { RecordPositionService } from 'src/engine/core-modules/record-position/services/record-position.service';import { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';+import { PermissionsException } from 'src/engine/metadata-modules/permissions/permissions.exception';import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';@@ -27,6 +28,8 @@ 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 { isWorkflowAiAgentAction } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/guards/is-workflow-ai-agent-action.guard';+import { isWorkflowSendChatMessageAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/guards/is-workflow-send-chat-message-action.guard';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 {@@ -506,9 +509,15 @@ export class WorkflowRunWorkspaceService {return null;}- return (- workflowRun.state?.flow?.steps?.find((step) => step.id === stepId) ?? null+ const step = workflowRun.state?.flow?.steps?.find(+ (candidateStep) => candidateStep.id === stepId,);++ // a form step is submitted from its run, even one that older versions gave a conversation+ return isDefined(step) &&+ (isWorkflowAiAgentAction(step) || isWorkflowSendChatMessageAction(step))+ ? step+ : null;}// a step posting a call still runs until its executor marks it pending, and an answer may arrive first;@@ -644,6 +653,30 @@ export class WorkflowRunWorkspaceService {}, authContext);}+ // read with the requester's own permissions, which follow the visibility of the run's workflow+ async isWorkflowRunReadableByRequester(+ workflowRunId: string,+ ): Promise<boolean> {+ try {+ const workflowRun =+ await this.workspaceOrmManager.executeInWorkspaceContext(() =>+ this.workspaceOrmManager+ .getRepositoryWithContextPermissions<WorkflowRunWorkspaceEntity>(+ 'workflowRun',+ )+ .findOne({ where: { id: workflowRunId }, select: { id: true } }),+ );++ return isDefined(workflowRun);+ } catch (error) {+ if (error instanceof PermissionsException) {+ return false;+ }++ throw error;+ }+ }+async getWorkflowRunOrFail({workflowRunId,workspaceId,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 0f5a6951b2d..e1025d84bc4 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,14 +1,18 @@import { Injectable } from '@nestjs/common';+import { isString } from '@sniptt/guards';import { type ActorMetadata } from 'twenty-shared/types';-import { isDefined } from 'twenty-shared/utils';+import { isDefined, isPlainObject, isValidUuid } from 'twenty-shared/utils';import { StepStatus } from 'twenty-shared/workflow';import { msg } from '@lingui/core/macro';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 { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';+import {+ WorkflowRunStatus,+ type WorkflowRunWorkspaceEntity,+} 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 {WorkflowVersionStepException,@@ -107,47 +111,113 @@ export class WorkflowRunnerWorkspaceService {);}- // A form step completes with its answer; an agent step stays PENDING until the resume job claims it+ // a Send Message step completes with the answer; an agent step stays PENDING until the resume job claims itasync resumeAnsweredStep({workspaceId,workflowRunId,step,threadId,- response,toolResult,}: {workspaceId: string;workflowRunId: string;step: WorkflowAction;threadId: string;- response: Record<string, unknown>;toolResult: Record<string, unknown>;}): Promise<void> {// the member's answer already ran the call, so the step only reports itif (isWorkflowSendChatMessageAction(step)) {- await this.completeAnsweredStep({+ const hasCompletedStep =+ await this.workflowRunWorkspaceService.updateStepInfoIfPending({+ stepId: step.id,+ stepInfo: {+ status: StepStatus.SUCCESS,+ result: buildSendChatMessageAnswerResult({ threadId, toolResult }),+ },+ expectedThreadId: threadId,+ workspaceId,+ workflowRunId,+ });++ if (hasCompletedStep) {+ await this.resume({+ workspaceId,+ workflowRunId,+ lastExecutedStepId: step.id,+ });+ }++ return;+ }++ await this.messageQueueService.add<RunWorkflowJobData>(+ RunWorkflowJob.name,+ {workspaceId,workflowRunId,- stepId: step.id,- threadId,- result: buildSendChatMessageAnswerResult({ threadId, toolResult }),+ stepToResume: { stepId: step.id, threadId },+ },+ buildRunWorkflowJobOptions(workflowRunId),+ );+ }++ async submitFormStep({+ workspaceId,+ workflowRunId,+ stepId,+ response,+ }: {+ workspaceId: string;+ workflowRunId: string;+ stepId: string;+ response: Record<string, unknown>;+ }): Promise<void> {+ const workflowRun =+ await this.workflowRunWorkspaceService.getWorkflowRunOrFail({+ workflowRunId,+ workspaceId,});- return;+ const step = workflowRun.state?.flow?.steps?.find(+ (candidateStep) => candidateStep.id === stepId,+ );++ if (!isDefined(step) || !isWorkflowFormAction(step)) {+ throw new WorkflowVersionStepException(+ 'Step is not a form step of this run',+ WorkflowVersionStepExceptionCode.NOT_FOUND,+ );}- if (!isWorkflowFormAction(step)) {- await this.messageQueueService.add<RunWorkflowJobData>(- RunWorkflowJob.name,- {- workspaceId,- workflowRunId,- stepToResume: { stepId: step.id, threadId },- },- buildRunWorkflowJobOptions(workflowRunId),+ const fieldNames = new Set(step.settings.input.map((field) => field.name));++ if (Object.keys(response).some((key) => !fieldNames.has(key))) {+ throw new WorkflowVersionStepException(+ 'Form response holds values for fields the form does not have',+ WorkflowVersionStepExceptionCode.INVALID_REQUEST,);+ }- return;+ // a pick that is not a record id would skip the permission check when the response is enriched+ const hasMalformedRecordPick = step.settings.input.some((field) => {+ const value = response[field.name];++ return (+ field.type === 'RECORD' &&+ isDefined(value) &&+ !(+ isPlainObject(value) &&+ (!isDefined(value.id) ||+ (isString(value.id) && isValidUuid(value.id)))+ )+ );+ });++ if (hasMalformedRecordPick) {+ throw new WorkflowVersionStepException(+ 'A record field of the form holds no valid record id',+ WorkflowVersionStepExceptionCode.INVALID_REQUEST,+ );}const enrichedResponse =@@ -158,74 +228,62 @@ export class WorkflowRunnerWorkspaceService {response,recordReadContext: await this.findFormRecordReadContext({workspaceId,- workflowRunId,+ workflowRun,step,}),},);- await this.completeAnsweredStep({- workspaceId,- workflowRunId,- stepId: step.id,- threadId,- result: enrichedResponse,- });- }-- private async completeAnsweredStep({- workspaceId,- workflowRunId,- stepId,- threadId,- result,- }: {- workspaceId: string;- workflowRunId: string;- stepId: string;- threadId: string;- result: object;- }): Promise<void> {const hasCompletedStep =await this.workflowRunWorkspaceService.updateStepInfoIfPending({stepId,- stepInfo: {- status: StepStatus.SUCCESS,- result,- },- expectedThreadId: threadId,+ stepInfo: { status: StepStatus.SUCCESS, result: enrichedResponse },workspaceId,workflowRunId,});- if (hasCompletedStep) {+ if (!hasCompletedStep) {+ throw new WorkflowVersionStepException(+ 'Form step is no longer waiting for an answer',+ WorkflowVersionStepExceptionCode.INVALID_REQUEST,+ {+ userFriendlyMessage: msg`This form no longer waits for an answer.`,+ },+ );+ }++ // the step is no longer pending, so a submission cannot be retried and the run must not stay running+ try {await this.resume({workspaceId,workflowRunId,lastExecutedStepId: stepId,});+ } catch (error) {+ await this.workflowRunWorkspaceService.endWorkflowRun({+ workflowRunId,+ workspaceId,+ status: WorkflowRunStatus.FAILED,+ error: 'The run could not resume after its form was submitted',+ });++ throw error;}}private async findFormRecordReadContext({workspaceId,- workflowRunId,+ workflowRun,step,}: {workspaceId: string;- workflowRunId: string;+ workflowRun: WorkflowRunWorkspaceEntity;step: WorkflowFormAction;}): Promise<WorkflowExecutionContext | undefined> {if (!step.settings.input.some((field) => field.type === 'RECORD')) {return undefined;}- const workflowRun =- await this.workflowRunWorkspaceService.getWorkflowRunOrFail({- workflowRunId,- workspaceId,- });-const applicationBoundExecutionContext =await this.workflowExecutionContextService.getApplicationBoundExecutionContext({ workflowRun, workspaceId })diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/application-workflow-execution-permissions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/application-workflow-execution-permissions.integration-spec.tsindex 0e8301020d1..11cd3306800 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/application-workflow-execution-permissions.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/application-workflow-execution-permissions.integration-spec.ts@@ -1,7 +1,7 @@import { randomUUID } from 'node:crypto';import request from 'supertest';-import { answerToolCall } from 'test/integration/graphql/suites/workflow/utils/answer-tool-call.util';+import { submitFormStep } from 'test/integration/graphql/suites/workflow/utils/submit-form-step.util';import { runWorkflowActionStep } from 'test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util';import { workflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/workflow-graphql-request.util';import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';@@ -611,20 +611,8 @@ describe('application workflow execution permissions', () => {expect(filledStep.body.errors).toBeUndefined();}, 120000);- it('reads the records picked in a form with the permissions of the run', async () => {+ it('reads the records picked in a form with the permissions of the run, keeping a refused form open', async () => {const [formStep] = FORM_WORKFLOW.steps;- const startFormRun = async () => {- const workflowRunId = await runWorkflow(FORM_WORKFLOW);-- await waitForRun(- workflowRunId,- ({ state }) =>- state?.stepInfos?.[formStep.universalIdentifier]?.status ===- 'PENDING',- );-- return workflowRunId;- };const [opportunity] = await globalThis.testDataSource.query(`SELECT id FROM "${SCHEMA}"."opportunity" WHERE "deletedAt" IS NULL LIMIT 1`,@@ -633,35 +621,51 @@ describe('application workflow execution permissions', () => {`SELECT id FROM "${SCHEMA}"."company" WHERE "deletedAt" IS NULL LIMIT 1`,);- const unreadableRunId = await startFormRun();- const unreadableSelection = await answerToolCall({- toolCall: {- workflowRunId: unreadableRunId,- stepId: formStep.universalIdentifier,- },+ const formRunId = await runWorkflow(FORM_WORKFLOW);++ await waitForRun(+ formRunId,+ ({ state }) =>+ state?.stepInfos?.[formStep.universalIdentifier]?.status === 'PENDING',+ );++ const unreadableSelection = await submitFormStep({+ workflowRunId: formRunId,+ stepId: formStep.universalIdentifier,response: { opportunity: { id: opportunity.id } },});expect(unreadableSelection.body.errors).toBeDefined();- expect((await waitForRunToEnd(unreadableRunId)).status).toBe('FAILED');+ expect(+ (await findRun(formRunId)).state.stepInfos[formStep.universalIdentifier]+ .status,+ ).toBe('PENDING');++ const malformedSelection = await submitFormStep({+ workflowRunId: formRunId,+ stepId: formStep.universalIdentifier,+ response: { company: { id: 'not-a-record-id' } },+ });- const readableRunId = await startFormRun();- const readableSelection = await answerToolCall({- toolCall: {- workflowRunId: readableRunId,- stepId: formStep.universalIdentifier,- },+ expect(malformedSelection.body.errors).toBeDefined();++ const readableSelection = await submitFormStep({+ workflowRunId: formRunId,+ stepId: formStep.universalIdentifier,response: { company: { id: company.id } },});expect(readableSelection.body.errors).toBeUndefined();- const workflowRun = await waitForRunToEnd(readableRunId);+ const workflowRun = await waitForRunToEnd(formRunId);expect(workflowRun.status).toBe('COMPLETED');expect(workflowRun.state.stepInfos[formStep.universalIdentifier].result,).toMatchObject({ company: { id: company.id } });+ expect(+ workflowRun.state.stepInfos[formStep.universalIdentifier].result,+ ).not.toHaveProperty('opportunity');}, 120000);it('checks the current application permissions again when a delayed run resumes', async () => {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 0d5be7a39d5..183a925151e 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@@ -27,6 +27,7 @@ import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/typimport { 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 { answerToolCall } from 'test/integration/graphql/suites/workflow/utils/answer-tool-call.util';+import { submitFormStep } from 'test/integration/graphql/suites/workflow/utils/submit-form-step.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 AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';@@ -742,8 +743,9 @@ describe('core workflow execution and queue compatibility (e2e)', () => {await waitForStep(runId, form.id, 'PENDING');await migratePendingRun(fixture, runId);await clearDefinitions(fixture);- const response = await answerToolCall({- toolCall: { workflowRunId: runId, stepId: form.id },+ const response = await submitFormStep({+ workflowRunId: runId,+ stepId: form.id,response: { answer: 'From the stored form' },});@@ -781,43 +783,21 @@ describe('core workflow execution and queue compatibility (e2e)', () => {runId: string;stepId: string;answer: string;- }) =>- answerToolCall({- toolCall: { workflowRunId: runId, stepId },- response: { answer },- });+ }) => submitFormStep({ workflowRunId: runId, stepId, response: { answer } });- describe('the conversation a form step records', () => {- const approvalForm = (nextStepIds: string[]): WorkflowAction => ({- ...formStep(nextStepIds),- name: 'Approve the discount',- });-- 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],+ describe('submitting a form step', () => {+ const countRunConversations = async (runId: string) => {+ const [{ count }] = await global.testDataSource.query(+ `SELECT COUNT(*)::int AS count FROM "${schema}"."agentChatThread" WHERE "workflowRunId" = $1`,+ [runId],);- 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,- };+ return count;};- it('asks for the fields in a request_form call while the form waits, and records the answer on submit', async () => {+ it('waits without a conversation and completes with the submitted values', async () => {const finalStep = emptyStep();- const form = approvalForm([finalStep.id]);+ const form = formStep([finalStep.id]);const fixture = await createFixture({mirrorless: true,steps: [form, finalStep],@@ -826,13 +806,10 @@ describe('core workflow execution and queue compatibility (e2e)', () => {await waitForStep(runId, form.id, 'PENDING');- expect(await getFormConversation(runId, form.id)).toMatchObject({- title: 'Approve the discount',- isWaiting: true,- toolName: 'request_form',- toolInput: { fields: form.settings.input },- status: 'pending',- });+ expect((await getRun(runId)).state.stepInfos[form.id].threadId).toBe(+ undefined,+ );+ expect(await countRunConversations(runId)).toBe(0);const response = await submitForm({runId,@@ -841,18 +818,18 @@ describe('core workflow execution and queue compatibility (e2e)', () => {});expect(response.body.errors).toBeUndefined();- await waitForRun(runId, 'COMPLETED');- expect(await getFormConversation(runId, form.id)).toMatchObject({- isWaiting: false,- status: 'answered',- values: { answer: 'Approved' },+ const run = await waitForRun(runId, 'COMPLETED');++ expect(run.state.stepInfos[form.id].result).toEqual({+ answer: 'Approved',});+ expect(await countRunConversations(runId)).toBe(0);});- it('refuses a submission whose answer cannot be recorded, leaving the form waiting', async () => {+ it('refuses values for fields the form does not have', async () => {const finalStep = emptyStep();- const form = approvalForm([finalStep.id]);+ const form = formStep([finalStep.id]);const fixture = await createFixture({mirrorless: true,steps: [form, finalStep],@@ -861,40 +838,21 @@ describe('core workflow execution and queue compatibility (e2e)', () => {await waitForStep(runId, form.id, 'PENDING');- const recordToolCallAnswer = jest- .spyOn(- getAppProviderByClassName<AgentChatService>('AgentChatService'),- 'recordToolCallAnswer',- )- .mockRejectedValueOnce(new Error('Answer write failed'));-- const refused = await submitForm({- runId,+ const refused = await submitFormStep({+ workflowRunId: runId,stepId: form.id,- answer: 'Approved',+ response: { unknownField: 'Approved' },});- recordToolCallAnswer.mockRestore();-expect(refused.body.errors).toBeDefined();expect((await getRun(runId)).state.stepInfos[form.id].status).toBe('PENDING',);- 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');});it('refuses a second submission and keeps the first answer', async () => {const finalStep = emptyStep();- const form = approvalForm([finalStep.id]);+ const form = formStep([finalStep.id]);const fixture = await createFixture({mirrorless: true,steps: [form, finalStep],@@ -919,19 +877,16 @@ describe('core workflow execution and queue compatibility (e2e)', () => {});expect(JSON.stringify(second.body.errors)).toContain(- 'TOOL_CALL_NOT_PENDING',+ 'no longer waiting for an answer',);expect((await getRun(runId)).state.stepInfos[form.id].result).toEqual({answer: 'Approved',});- expect(await getFormConversation(runId, form.id)).toMatchObject({- values: { answer: 'Approved' },- });});- it('records a conversation for each iteration of a form inside a loop', async () => {+ it('takes a submission for each iteration of a form inside a loop', async () => {const afterLoop = emptyStep();- const form = approvalForm([]);+ const form = formStep([]);const iterator: WorkflowAction = {...emptyStep(),type: WorkflowActionType.ITERATOR,@@ -955,11 +910,6 @@ describe('core workflow execution and queue compatibility (e2e)', () => {await waitForStep(runId, form.id, 'PENDING');- const { threadId: firstThreadId } = await getFormConversation(- runId,- form.id,- );-const first = await submitForm({runId,stepId: form.id,@@ -969,14 +919,6 @@ describe('core workflow execution and queue compatibility (e2e)', () => {expect(first.body.errors).toBeUndefined();await waitForStep(runId, form.id, 'PENDING');- const secondConversation = await getFormConversation(runId, form.id);-- expect(secondConversation.threadId).not.toBe(firstThreadId);- expect(secondConversation).toMatchObject({- isWaiting: true,- status: 'pending',- });-const second = await submitForm({runId,stepId: form.id,@@ -984,15 +926,17 @@ describe('core workflow execution and queue compatibility (e2e)', () => {});expect(second.body.errors).toBeUndefined();- await waitForRun(runId, 'COMPLETED');- expect(await getFormConversation(runId, form.id)).toMatchObject({- values: { answer: 'Second item' },++ const run = await waitForRun(runId, 'COMPLETED');++ expect(run.state.stepInfos[form.id].result).toEqual({+ answer: 'Second item',});});- it('closes the call when its run ends before anyone answers', async () => {+ it('refuses a submission once its run ended', async () => {const finalStep = emptyStep();- const form = approvalForm([finalStep.id]);+ const form = formStep([finalStep.id]);const fixture = await createFixture({mirrorless: true,steps: [form, finalStep],@@ -1008,10 +952,6 @@ describe('core workflow execution and queue compatibility (e2e)', () => {expect(response.body.errors).toBeUndefined();await waitForRun(runId, 'STOPPED');- expect(await getFormConversation(runId, form.id)).toMatchObject({- isWaiting: false,- status: 'skipped',- });const late = await submitForm({runId,@@ -1020,7 +960,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {});expect(JSON.stringify(late.body.errors)).toContain(- 'TOOL_CALL_NOT_PENDING',+ 'no longer waiting for an answer',);const run = await getRun(runId);@@ -1054,7 +994,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {});expect(JSON.stringify(response.body.errors)).toContain(- 'TOOL_CALL_NOT_PENDING',+ 'no longer waiting for an answer',);expect((await getRun(runId)).state.stepInfos[form.id].status).toBe('PENDING',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 1dc61fe3623..91a98bdc49c 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,7 +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 { submitFormStep } from 'test/integration/graphql/suites/workflow/utils/submit-form-step.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';@@ -323,13 +323,14 @@ describe('Parallel branch leaf resume workflow (e2e)', () => {'NOT_STARTED',);- const submitFormResponse = await answerToolCall({- toolCall: { workflowRunId: createdWorkflowRunId, stepId: formStepId! },+ const submitFormResponse = await submitFormStep({+ workflowRunId: createdWorkflowRunId,+ stepId: formStepId!,response: { answer: 'Submitted from integration test' },});expect(submitFormResponse.body.errors).toBeUndefined();- expect(submitFormResponse.body.data.answerToolCall.streamId).toBeNull();+ expect(submitFormResponse.body.data.submitFormStep).toBe(true);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 d684b1dc2e0..25c3ba84bdf 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 { answerToolCall } from 'test/integration/graphql/suites/workflow/utils/answer-tool-call.util';+import { submitFormStep } from 'test/integration/graphql/suites/workflow/utils/submit-form-step.util';import {destroyWorkflowRun,getWorkflowRun,@@ -269,16 +269,14 @@ describe('Quick Lead Workflow (e2e)', () => {companyDomain: `https://test-${testId}.example.com`,};- const submitFormResponse = await answerToolCall({- toolCall: {- workflowRunId: testWorkflowRunId as string,- stepId: FORM_STEP_ID,- },+ const submitFormResponse = await submitFormStep({+ workflowRunId: testWorkflowRunId as string,+ stepId: FORM_STEP_ID,response: testFormData,});expect(submitFormResponse.body.errors).toBeUndefined();- expect(submitFormResponse.body.data.answerToolCall.streamId).toBeNull();+ expect(submitFormResponse.body.data.submitFormStep).toBe(true);workflowRun = await waitForWorkflowCompletion(testWorkflowRunId as string,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.tsindex 08c9d7d0e1e..c4a8492914b 100644--- 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.ts@@ -1,45 +1,13 @@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 };--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;+ toolCall: { threadId: string; toolCallId: string };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,- },- },+ { input: { ...toolCall, response } },);diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/submit-form-step.util.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/submit-form-step.util.tsnew file mode 100644index 00000000000..e3a0bba7b21--- /dev/null+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/submit-form-step.util.ts@@ -0,0 +1,15 @@+import { workflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/workflow-graphql-request.util';++export const submitFormStep = ({+ workflowRunId,+ stepId,+ response,+}: {+ workflowRunId: string;+ stepId: string;+ response: Record<string, unknown>;+}) =>+ workflowGraphqlRequest(+ 'mutation SubmitFormStep($input: SubmitFormStepInput!) { submitFormStep(input: $input) }',+ { input: { workflowRunId, stepId, response } },+ );diff --git a/packages/twenty-shared/src/ai/types/RequestFormToolInput.ts b/packages/twenty-shared/src/ai/types/RequestFormToolInput.tsindex 7537f24fcd1..8f665a9b68e 100644--- a/packages/twenty-shared/src/ai/types/RequestFormToolInput.ts+++ b/packages/twenty-shared/src/ai/types/RequestFormToolInput.ts@@ -2,7 +2,6 @@ import type z from 'zod';import { type workflowFormFieldSchema } from '@/workflow/schemas/form-action-settings-schema';-// Workflow form steps issue this call too, so they and agent form requests are answered alike; answers are keyed by field name.export type RequestFormField = Pick<z.infer<typeof workflowFormFieldSchema>,'name' | 'label' | 'type' | 'placeholder' | 'settings'