Skip to content

The open alternative to Salesforce, designed for AI.

POC: define application workflows through the SDK (#26662)

Thomas Trompette96714a0e4d67
diff --git a/packages/twenty-client-sdk/project.json b/packages/twenty-client-sdk/project.json
index a7342268a48..19440c1e3f7 100644
--- a/packages/twenty-client-sdk/project.json
+++ b/packages/twenty-client-sdk/project.json
@@ -14,7 +14,7 @@
"options": {
"cwd": "{projectRoot}",
"commands": [
- "npx rimraf dist && npx vite build && npx vite build -c vite.metadata.config.ts",
+ "npx rimraf dist && NODE_ENV=production npx vite build && NODE_ENV=production npx vite build -c vite.metadata.config.ts",
"tsgo -p tsconfig.lib.json --declaration --emitDeclarationOnly --noEmit false --outDir dist --rootDir src && npx tsc-alias -p tsconfig.lib.json --outDir dist"
],
"parallel": false
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 54dd8c87327..96c4c6e45f7 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -2069,6 +2069,7 @@ type FeatureFlag {
}
enum FeatureFlagKey {
+ IS_APPLICATION_WORKFLOWS_ENABLED
IS_ASYNC_CSV_EXPORT_ENABLED
IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED
IS_JSON_FILTER_ENABLED
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 7dfaae6b171..9baeef40015 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1683,7 +1683,7 @@ export interface FeatureFlag {
__typename: 'FeatureFlag'
}
-export type FeatureFlagKey = 'IS_ASYNC_CSV_EXPORT_ENABLED' | 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_MESSAGE_CAMPAIGN_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' | 'IS_AI_CHAT_SHARING_DROPDOWN_ENABLED' | 'IS_INITIAL_OBJECT_VIEW_ENABLED' | 'IS_WEBHOOK_RATE_LIMIT_ENABLED' | 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED' | 'IS_EXECUTION_QUOTA_ENABLED' | 'IS_RECORD_CREATION_FORM_ENABLED' | 'IS_LOGS_SETTINGS_SECTION_ENABLED' | 'IS_CONVERSATIONS_TAB_ENABLED' | 'IS_VALIDATION_RULES_ENABLED'
+export type FeatureFlagKey = 'IS_APPLICATION_WORKFLOWS_ENABLED' | 'IS_ASYNC_CSV_EXPORT_ENABLED' | 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_MESSAGE_CAMPAIGN_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' | 'IS_AI_CHAT_SHARING_DROPDOWN_ENABLED' | 'IS_INITIAL_OBJECT_VIEW_ENABLED' | 'IS_WEBHOOK_RATE_LIMIT_ENABLED' | 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED' | 'IS_EXECUTION_QUOTA_ENABLED' | 'IS_RECORD_CREATION_FORM_ENABLED' | 'IS_LOGS_SETTINGS_SECTION_ENABLED' | 'IS_CONVERSATIONS_TAB_ENABLED' | 'IS_VALIDATION_RULES_ENABLED'
export interface WorkspaceUrls {
customUrl?: Scalars['String']
@@ -11271,6 +11271,7 @@ export const enumEmailConnectionSecurity = {
}
export const enumFeatureFlagKey = {
+ IS_APPLICATION_WORKFLOWS_ENABLED: 'IS_APPLICATION_WORKFLOWS_ENABLED' as const,
IS_ASYNC_CSV_EXPORT_ENABLED: 'IS_ASYNC_CSV_EXPORT_ENABLED' as const,
IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED: 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' as const,
IS_JSON_FILTER_ENABLED: 'IS_JSON_FILTER_ENABLED' as const,
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.ts
index 625c810848f..0c40e342798 100644
--- a/packages/twenty-front/src/generated-admin/graphql.ts
+++ b/packages/twenty-front/src/generated-admin/graphql.ts
@@ -476,6 +476,7 @@ export type FeatureFlag = {
export enum FeatureFlagKey {
IS_AI_CHAT_SHARING_DROPDOWN_ENABLED = 'IS_AI_CHAT_SHARING_DROPDOWN_ENABLED',
+ IS_APPLICATION_WORKFLOWS_ENABLED = 'IS_APPLICATION_WORKFLOWS_ENABLED',
IS_ASYNC_CSV_EXPORT_ENABLED = 'IS_ASYNC_CSV_EXPORT_ENABLED',
IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED = 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED',
IS_CONVERSATIONS_TAB_ENABLED = 'IS_CONVERSATIONS_TAB_ENABLED',
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 4075c60bb1a..4cdde1c4716 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -2131,6 +2131,7 @@ export type FeatureFlag = {
export enum FeatureFlagKey {
IS_AI_CHAT_SHARING_DROPDOWN_ENABLED = 'IS_AI_CHAT_SHARING_DROPDOWN_ENABLED',
+ IS_APPLICATION_WORKFLOWS_ENABLED = 'IS_APPLICATION_WORKFLOWS_ENABLED',
IS_ASYNC_CSV_EXPORT_ENABLED = 'IS_ASYNC_CSV_EXPORT_ENABLED',
IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED = 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED',
IS_CONVERSATIONS_TAB_ENABLED = 'IS_CONVERSATIONS_TAB_ENABLED',
diff --git a/packages/twenty-front/src/generated/graphql.ts b/packages/twenty-front/src/generated/graphql.ts
index 4affd13d390..44f6b1978a6 100644
--- a/packages/twenty-front/src/generated/graphql.ts
+++ b/packages/twenty-front/src/generated/graphql.ts
@@ -1352,7 +1352,7 @@ export type GetCoreWorkflowQueryVariables = Exact<{
}>;
-export type GetCoreWorkflowQuery = { __typename?: 'Query', coreWorkflow?: { __typename?: 'CoreWorkflowDTO', id: any, name?: string | null, statuses: Array<CoreWorkflowStatus>, lastPublishedCoreWorkflowVersionId?: any | null, workspaceWorkflowId?: any | null, visibility: WorkflowVisibility, canChangeVisibility: boolean, createdAt: string, updatedAt: string } | null };
+export type GetCoreWorkflowQuery = { __typename?: 'Query', coreWorkflow?: { __typename?: 'CoreWorkflowDTO', id: any, name?: string | null, statuses: Array<CoreWorkflowStatus>, lastPublishedCoreWorkflowVersionId?: any | null, applicationId?: any | null, workspaceWorkflowId?: any | null, visibility: WorkflowVisibility, canChangeVisibility: boolean, createdAt: string, updatedAt: string } | null };
export type GetCoreWorkflowLegacyMappingQueryVariables = Exact<{
workspaceWorkflowId: Scalars['UUID']['input'];
@@ -1384,7 +1384,7 @@ export type GetCoreWorkflowsWithCurrentVersionsQueryVariables = Exact<{
}>;
-export type GetCoreWorkflowsWithCurrentVersionsQuery = { __typename?: 'Query', coreWorkflowsWithCurrentVersions: Array<{ __typename?: 'CoreWorkflowWithCurrentVersionDTO', workflow: { __typename?: 'CoreWorkflowDTO', id: any, name?: string | null, statuses: Array<CoreWorkflowStatus>, lastPublishedCoreWorkflowVersionId?: any | null }, versions: Array<{ __typename?: 'CoreWorkflowVersionDTO', id: any, coreWorkflowId?: any | null, label: string, status: CoreWorkflowVersionStatus, createdAt: string }>, currentVersion: { __typename?: 'CoreWorkflowVersionDTO', id: any, coreWorkflowId?: any | null, label: string, status: CoreWorkflowVersionStatus, trigger?: any | null, steps?: any | null, createdAt: string, updatedAt: string } }> };
+export type GetCoreWorkflowsWithCurrentVersionsQuery = { __typename?: 'Query', coreWorkflowsWithCurrentVersions: Array<{ __typename?: 'CoreWorkflowWithCurrentVersionDTO', workflow: { __typename?: 'CoreWorkflowDTO', id: any, name?: string | null, applicationId?: any | null, statuses: Array<CoreWorkflowStatus>, lastPublishedCoreWorkflowVersionId?: any | null }, versions: Array<{ __typename?: 'CoreWorkflowVersionDTO', id: any, coreWorkflowId?: any | null, label: string, status: CoreWorkflowVersionStatus, createdAt: string }>, currentVersion: { __typename?: 'CoreWorkflowVersionDTO', id: any, coreWorkflowId?: any | null, label: string, status: CoreWorkflowVersionStatus, trigger?: any | null, steps?: any | null, createdAt: string, updatedAt: string } }> };
export type GetCoreWorkflowVersionQueryVariables = Exact<{
coreWorkflowVersionId: Scalars['UUID']['input'];
@@ -1572,11 +1572,11 @@ export const UpdateCoreWorkflowVersionPositionsDocument = {"kind":"Document","de
export const UpdateCoreWorkflowVersionStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateCoreWorkflowVersionStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateCoreWorkflowVersionStepInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"updateWorkflowVersionStep"},"name":{"kind":"Name","value":"updateCoreWorkflowVersionStep"},"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<UpdateCoreWorkflowVersionStepMutation, UpdateCoreWorkflowVersionStepMutationVariables>;
export const UpdateCoreWorkflowVersionTriggerDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateCoreWorkflowVersionTrigger"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateCoreWorkflowVersionTriggerInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"updateWorkflowVersionTrigger"},"name":{"kind":"Name","value":"updateCoreWorkflowVersionTrigger"},"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<UpdateCoreWorkflowVersionTriggerMutation, UpdateCoreWorkflowVersionTriggerMutationVariables>;
export const UpdateCoreWorkflowVisibilityDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateCoreWorkflowVisibility"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateCoreWorkflowVisibilityInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateCoreWorkflowVisibility"},"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":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"canChangeVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<UpdateCoreWorkflowVisibilityMutation, UpdateCoreWorkflowVisibilityMutationVariables>;
-export const GetCoreWorkflowDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflow"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"coreWorkflow"},"name":{"kind":"Name","value":"coreWorkflowById"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"coreWorkflowId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowId"}}}],"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":"lastPublishedCoreWorkflowVersionId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"canChangeVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowQuery, GetCoreWorkflowQueryVariables>;
+export const GetCoreWorkflowDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflow"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"coreWorkflow"},"name":{"kind":"Name","value":"coreWorkflowById"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"coreWorkflowId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowId"}}}],"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":"lastPublishedCoreWorkflowVersionId"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"canChangeVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowQuery, GetCoreWorkflowQueryVariables>;
export const GetCoreWorkflowLegacyMappingDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflowLegacyMapping"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceWorkflowId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"coreWorkflow"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceWorkflowId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceWorkflowId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowLegacyMappingQuery, GetCoreWorkflowLegacyMappingQueryVariables>;
export const GetCoreWorkflowVersionLegacyMappingDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflowVersionLegacyMapping"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceWorkflowVersionId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowVersion"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceWorkflowVersionId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceWorkflowVersionId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowVersionId"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowVersionLegacyMappingQuery, GetCoreWorkflowVersionLegacyMappingQueryVariables>;
export const GetCoreWorkflowsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflows"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"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":"orderBy"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"CoreWorkflowOrderByField"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"orderByDirection"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"CoreWorkflowOrderByDirection"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"filter"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"CoreWorkflowFilterInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"coreWorkflows"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}},{"kind":"Argument","name":{"kind":"Name","value":"orderBy"},"value":{"kind":"Variable","name":{"kind":"Name","value":"orderBy"}}},{"kind":"Argument","name":{"kind":"Name","value":"orderByDirection"},"value":{"kind":"Variable","name":{"kind":"Name","value":"orderByDirection"}}},{"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":"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":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"canChangeVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cursor"}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"endCursor"}},{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}}]}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowsQuery, GetCoreWorkflowsQueryVariables>;
-export const GetCoreWorkflowsWithCurrentVersionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflowsWithCurrentVersions"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CoreWorkflowsWithCurrentVersionsInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowsWithCurrentVersions"},"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":"workflow"},"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":"lastPublishedCoreWorkflowVersionId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"versions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"currentVersion"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"trigger"}},{"kind":"Field","name":{"kind":"Name","value":"steps"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowsWithCurrentVersionsQuery, GetCoreWorkflowsWithCurrentVersionsQueryVariables>;
+export const GetCoreWorkflowsWithCurrentVersionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflowsWithCurrentVersions"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CoreWorkflowsWithCurrentVersionsInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowsWithCurrentVersions"},"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":"workflow"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"statuses"}},{"kind":"Field","name":{"kind":"Name","value":"lastPublishedCoreWorkflowVersionId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"versions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"currentVersion"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"trigger"}},{"kind":"Field","name":{"kind":"Name","value":"steps"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowsWithCurrentVersionsQuery, GetCoreWorkflowsWithCurrentVersionsQueryVariables>;
export const GetCoreWorkflowVersionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflowVersion"},"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":"coreWorkflowVersion"},"name":{"kind":"Name","value":"coreWorkflowVersionById"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"coreWorkflowVersionId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowVersionId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowVersionId"}},{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"trigger"}},{"kind":"Field","name":{"kind":"Name","value":"steps"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowVersionQuery, GetCoreWorkflowVersionQueryVariables>;
export const GetCoreWorkflowVersionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflowVersions"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"coreWorkflowVersions"},"name":{"kind":"Name","value":"coreWorkflowVersionsByCoreWorkflowId"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"coreWorkflowId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowVersionsQuery, GetCoreWorkflowVersionsQueryVariables>;
export const ActivateWorkflowVersionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ActivateWorkflowVersion"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workflowVersionId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"activateWorkflowVersion"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workflowVersionId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workflowVersionId"}}}]}]}}]} as unknown as DocumentNode<ActivateWorkflowVersionMutation, ActivateWorkflowVersionMutationVariables>;
diff --git a/packages/twenty-front/src/modules/applications/hooks/useIsThirdPartyApplication.ts b/packages/twenty-front/src/modules/applications/hooks/useIsThirdPartyApplication.ts
index 2cb5bf77802..3cb8aec1101 100644
--- a/packages/twenty-front/src/modules/applications/hooks/useIsThirdPartyApplication.ts
+++ b/packages/twenty-front/src/modules/applications/hooks/useIsThirdPartyApplication.ts
@@ -1,5 +1,4 @@
-import { isTwentyStandardApplication } from '@/applications/utils/isTwentyStandardApplication';
-import { isWorkspaceCustomApplication } from '@/applications/utils/isWorkspaceCustomApplication';
+import { isThirdPartyApplication } from '@/applications/utils/isThirdPartyApplication';
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { isDefined } from 'twenty-shared/utils';
@@ -17,9 +16,5 @@ export const useIsThirdPartyApplication = (
(app) => app.id === applicationId,
);
- return (
- isDefined(application) &&
- !isTwentyStandardApplication(application) &&
- !isWorkspaceCustomApplication(application, currentWorkspace)
- );
+ return isThirdPartyApplication({ application, currentWorkspace });
};
diff --git a/packages/twenty-front/src/modules/applications/utils/isThirdPartyApplication.ts b/packages/twenty-front/src/modules/applications/utils/isThirdPartyApplication.ts
new file mode 100644
index 00000000000..beb0bec03fb
--- /dev/null
+++ b/packages/twenty-front/src/modules/applications/utils/isThirdPartyApplication.ts
@@ -0,0 +1,26 @@
+import { isTwentyStandardApplication } from '@/applications/utils/isTwentyStandardApplication';
+import { isWorkspaceCustomApplication } from '@/applications/utils/isWorkspaceCustomApplication';
+import { isDefined } from 'twenty-shared/utils';
+
+type ApplicationLike = {
+ id?: string | null;
+ universalIdentifier?: string | null;
+};
+
+type WorkspaceLike = {
+ workspaceCustomApplication?: { id?: string | null } | null;
+};
+
+export const isThirdPartyApplication = ({
+ application,
+ currentWorkspace,
+}: {
+ application: ApplicationLike | null | undefined;
+ currentWorkspace: WorkspaceLike | null | undefined;
+}): boolean => {
+ return (
+ isDefined(application) &&
+ !isTwentyStandardApplication(application) &&
+ !isWorkspaceCustomApplication(application, currentWorkspace)
+ );
+};
diff --git a/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContextProviderWithWorkflowEnrichment.tsx b/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContextProviderWithWorkflowEnrichment.tsx
index 1655e7cdc06..6881debfc47 100644
--- a/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContextProviderWithWorkflowEnrichment.tsx
+++ b/packages/twenty-front/src/modules/command-menu-item/contexts/CommandMenuContextProviderWithWorkflowEnrichment.tsx
@@ -1,3 +1,6 @@
+import { isThirdPartyApplication } from '@/applications/utils/isThirdPartyApplication';
+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { type CommandMenuContextApi } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
@@ -26,6 +29,7 @@ export const CommandMenuContextProviderWithWorkflowEnrichment = ({
isInPreviewMode,
}: CommandMenuContextProviderWithWorkflowEnrichmentProps) => {
const isCore = useIsWorkflowCoreEnabled();
+ const currentWorkspace = useAtomStateValue(currentWorkspaceState);
const workflowsWithCurrentVersions = useWorkflowsWithCurrentVersions(
isCore ? [] : selectedWorkflowRecordIds,
);
@@ -37,6 +41,20 @@ export const CommandMenuContextProviderWithWorkflowEnrichment = ({
? coreWorkflowsWithCurrentVersions
: workflowsWithCurrentVersions;
+ const applicationManagedWorkflowIds = new Set(
+ coreWorkflowsWithCurrentVersions
+ .filter((workflow) =>
+ isThirdPartyApplication({
+ application: currentWorkspace?.installedApplications.find(
+ (installedApplication) =>
+ installedApplication.id === workflow.applicationId,
+ ),
+ currentWorkspace,
+ }),
+ )
+ .map((workflow) => workflow.id),
+ );
+
const enrichedSelectedRecords = commandMenuContextApi.selectedRecords.map(
(record) => {
const workflowWithCurrentVersion = workflows.find(
@@ -54,6 +72,14 @@ export const CommandMenuContextProviderWithWorkflowEnrichment = ({
statuses: workflowWithCurrentVersion.statuses,
lastPublishedVersionId:
workflowWithCurrentVersion.lastPublishedVersionId,
+ ...(applicationManagedWorkflowIds.has(record.id) && {
+ recordPermissions: {
+ ...record.recordPermissions,
+ canUpdate: false,
+ canSoftDelete: false,
+ canDelete: false,
+ },
+ }),
};
},
);
diff --git a/packages/twenty-front/src/modules/command-menu-item/contexts/__tests__/CommandMenuContextProviderWithWorkflowEnrichment.test.tsx b/packages/twenty-front/src/modules/command-menu-item/contexts/__tests__/CommandMenuContextProviderWithWorkflowEnrichment.test.tsx
new file mode 100644
index 00000000000..10d315ee417
--- /dev/null
+++ b/packages/twenty-front/src/modules/command-menu-item/contexts/__tests__/CommandMenuContextProviderWithWorkflowEnrichment.test.tsx
@@ -0,0 +1,176 @@
+import { render, screen } from '@testing-library/react';
+import { useContext } from 'react';
+import {
+ ContextStorePageType,
+ CoreObjectNameSingular,
+} from 'twenty-shared/types';
+
+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
+import { EMPTY_COMMAND_MENU_CONTEXT_API } from '@/command-menu-item/constants/EmptyCommandMenuContextApi';
+import { CommandMenuContext } from '@/command-menu-item/contexts/CommandMenuContext';
+import { CommandMenuContextProviderWithWorkflowEnrichment } from '@/command-menu-item/contexts/CommandMenuContextProviderWithWorkflowEnrichment';
+import { useCoreWorkflowsWithCurrentVersions } from '@/command-menu-item/hooks/useCoreWorkflowsWithCurrentVersions';
+import { commandMenuItemsSelector } from '@/command-menu-item/states/commandMenuItemsSelector';
+import { CommandMenuItemContainerType } from '@/command-menu-item/types/CommandMenuItemContainerType';
+import { type CommandMenuItemDefinition } from '@/command-menu-item/types/CommandMenuItemDefinition';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import {
+ EngineComponentKey,
+ CommandMenuItemAvailabilityType,
+} from '~/generated-metadata/graphql';
+
+jest.mock(
+ '@/command-menu-item/hooks/useGlobalRecordCreationCommandMenuItems',
+ () => ({
+ useGlobalRecordCreationCommandMenuItems: () => ({
+ hasGlobalRecordCreationCommandTemplate: false,
+ globalRecordCreationCommandMenuItems: [],
+ }),
+ }),
+);
+jest.mock('@/workflow/hooks/useIsWorkflowCoreEnabled', () => ({
+ useIsWorkflowCoreEnabled: () => true,
+}));
+jest.mock('@/command-menu-item/hooks/useWorkflowsWithCurrentVersions', () => ({
+ useWorkflowsWithCurrentVersions: () => [],
+}));
+jest.mock('@/command-menu-item/hooks/useCoreWorkflowsWithCurrentVersions');
+jest.mock(
+ '@/layout-customization/hooks/useIsLayoutCustomizationAllowedOnCurrentPage',
+ () => ({
+ useIsLayoutCustomizationAllowedOnCurrentPage: () => false,
+ }),
+);
+jest.mock('@/ui/utilities/state/jotai/hooks/useAtomStateValue');
+jest.mock('@/auth/states/currentWorkspaceState', () => ({
+ currentWorkspaceState: {},
+}));
+jest.mock('@/command-menu-item/states/commandMenuItemsSelector', () => ({
+ commandMenuItemsSelector: {},
+}));
+jest.mock('@/command-menu-item/edit/states/commandMenuItemsDraftState', () => ({
+ commandMenuItemsDraftState: {},
+}));
+jest.mock('@/page-layout/states/currentPageLayoutIdState', () => ({
+ currentPageLayoutIdState: {},
+ PageLayoutIdContext: jest.requireActual('react').createContext(undefined),
+}));
+
+const REQUIRES_UPDATE =
+ 'noneEquals(selectedRecords, "recordPermissions.canUpdate", false)';
+const REQUIRES_SOFT_DELETE =
+ 'noneEquals(selectedRecords, "recordPermissions.canSoftDelete", false)';
+
+const COMMANDS = (
+ [
+ [EngineComponentKey.TEST_WORKFLOW, 'Test workflow', null],
+ [EngineComponentKey.DUPLICATE_WORKFLOW, 'Duplicate', REQUIRES_UPDATE],
+ [EngineComponentKey.DEACTIVATE_WORKFLOW, 'Deactivate', REQUIRES_UPDATE],
+ [EngineComponentKey.TIDY_UP_WORKFLOW, 'Tidy up', REQUIRES_UPDATE],
+ [EngineComponentKey.DELETE_RECORDS, 'Delete', REQUIRES_SOFT_DELETE],
+ ] as const
+).map(([engineComponentKey, label, expression], position) => ({
+ id: engineComponentKey,
+ engineComponentKey,
+ label,
+ position,
+ isPinned: true,
+ availabilityType: CommandMenuItemAvailabilityType.RECORD_SELECTION,
+ conditionalAvailabilityExpression: expression,
+})) as CommandMenuItemDefinition[];
+
+const CURRENT_WORKSPACE = {
+ workspaceCustomApplication: { id: 'workspace-application' },
+ installedApplications: [
+ { id: 'workspace-application', universalIdentifier: 'workspace' },
+ { id: 'installed-application', universalIdentifier: 'installed' },
+ ],
+};
+
+const CommandButtons = () => {
+ const { commandMenuItems } = useContext(CommandMenuContext);
+
+ return commandMenuItems.map((command) => (
+ <button key={command.id}>{command.label}</button>
+ ));
+};
+
+const renderWorkflowCommands = (applicationId: string) => {
+ jest.mocked(useAtomStateValue).mockImplementation((state) => {
+ if (state === commandMenuItemsSelector) {
+ return COMMANDS;
+ }
+
+ return state === currentWorkspaceState ? CURRENT_WORKSPACE : null;
+ });
+ jest.mocked(useCoreWorkflowsWithCurrentVersions).mockReturnValue([
+ {
+ __typename: 'Workflow',
+ id: 'workflow',
+ name: 'Workflow',
+ applicationId,
+ statuses: ['ACTIVE'],
+ lastPublishedVersionId: 'version',
+ versions: [],
+ currentVersion: {
+ __typename: 'WorkflowVersion',
+ id: 'version',
+ name: 'v1',
+ status: 'ACTIVE',
+ trigger: null,
+ steps: [],
+ workflowId: 'workflow',
+ createdAt: '2026-09-30T00:00:00.000Z',
+ updatedAt: '2026-09-30T00:00:00.000Z',
+ },
+ },
+ ] as unknown as ReturnType<typeof useCoreWorkflowsWithCurrentVersions>);
+
+ return render(
+ <CommandMenuContextProviderWithWorkflowEnrichment
+ displayType="button"
+ containerType={CommandMenuItemContainerType.ShowPageHeader}
+ isInPreviewMode={false}
+ selectedWorkflowRecordIds={['workflow']}
+ commandMenuContextApi={{
+ ...EMPTY_COMMAND_MENU_CONTEXT_API,
+ pageType: ContextStorePageType.Record,
+ numberOfSelectedRecords: 1,
+ selectedRecords: [{ id: 'workflow' }],
+ objectMetadataItem: { nameSingular: CoreObjectNameSingular.Workflow },
+ }}
+ >
+ <CommandButtons />
+ </CommandMenuContextProviderWithWorkflowEnrichment>,
+ );
+};
+
+describe('workflow command availability', () => {
+ it('hides commands that change or delete a workflow installed by an application', () => {
+ renderWorkflowCommands('installed-application');
+
+ expect(screen.getByRole('button', { name: 'Test workflow' })).toBeVisible();
+ expect(
+ screen.queryByRole('button', { name: 'Duplicate' }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', { name: 'Deactivate' }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', { name: 'Tidy up' }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', { name: 'Delete' }),
+ ).not.toBeInTheDocument();
+ });
+
+ it('keeps every command on a workspace workflow', () => {
+ renderWorkflowCommands('workspace-application');
+
+ expect(screen.getByRole('button', { name: 'Test workflow' })).toBeVisible();
+ expect(screen.getByRole('button', { name: 'Duplicate' })).toBeVisible();
+ expect(screen.getByRole('button', { name: 'Deactivate' })).toBeVisible();
+ expect(screen.getByRole('button', { name: 'Tidy up' })).toBeVisible();
+ expect(screen.getByRole('button', { name: 'Delete' })).toBeVisible();
+ });
+});
diff --git a/packages/twenty-front/src/modules/command-menu-item/hooks/useCoreWorkflowsWithCurrentVersions.ts b/packages/twenty-front/src/modules/command-menu-item/hooks/useCoreWorkflowsWithCurrentVersions.ts
index a67e69658d8..a56fd27311b 100644
--- a/packages/twenty-front/src/modules/command-menu-item/hooks/useCoreWorkflowsWithCurrentVersions.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/hooks/useCoreWorkflowsWithCurrentVersions.ts
@@ -8,7 +8,9 @@ import { GetCoreWorkflowsWithCurrentVersionsDocument } from '~/generated/graphql
export const useCoreWorkflowsWithCurrentVersions = (
coreWorkflowIds: string[],
-): WorkflowWithCurrentVersion[] => {
+): (WorkflowWithCurrentVersion & {
+ applicationId: string | null | undefined;
+})[] => {
const apolloCoreClient = useApolloCoreClient();
const { data } = useQuery(
@@ -33,6 +35,7 @@ export const useCoreWorkflowsWithCurrentVersions = (
{
__typename: 'Workflow' as const,
id: workflow.id,
+ applicationId: workflow.applicationId,
name: workflow.name ?? '',
statuses: workflow.statuses,
lastPublishedVersionId:
diff --git a/packages/twenty-front/src/modules/object-core/components/CoreObjectIdentifierBar.tsx b/packages/twenty-front/src/modules/object-core/components/CoreObjectIdentifierBar.tsx
index d98437e1fe3..a8b4df8dec5 100644
--- a/packages/twenty-front/src/modules/object-core/components/CoreObjectIdentifierBar.tsx
+++ b/packages/twenty-front/src/modules/object-core/components/CoreObjectIdentifierBar.tsx
@@ -29,6 +29,7 @@ const StyledBar = styled.div`
`;
type CoreObjectIdentifierBarProps = {
+ isReadOnly?: boolean;
recordId: string;
name: string | null | undefined;
namePlaceholder: string;
@@ -40,6 +41,7 @@ export const CoreObjectIdentifierBar = ({
name,
namePlaceholder,
onRename,
+ isReadOnly = false,
}: CoreObjectIdentifierBarProps) => {
const [editedName, setEditedName] = useState<string>();
const allowRequestsToTwentyIcons = useAtomStateValue(
@@ -51,7 +53,7 @@ export const CoreObjectIdentifierBar = ({
);
const saveName = async () => {
- if (!isDefined(editedName)) {
+ if (isReadOnly || !isDefined(editedName)) {
return;
}
@@ -78,6 +80,7 @@ export const CoreObjectIdentifierBar = ({
<TitleInput
instanceId={`core-object-name-${recordId}`}
sizeVariant="sm"
+ disabled={isReadOnly}
value={editedName ?? name ?? ''}
placeholder={namePlaceholder}
textColor={
diff --git a/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflow.ts b/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflow.ts
index 6ffad19b1cc..e43f6fe8ef7 100644
--- a/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflow.ts
+++ b/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflow.ts
@@ -7,6 +7,7 @@ export const GET_CORE_WORKFLOW = gql`
name
statuses
lastPublishedCoreWorkflowVersionId
+ applicationId
workspaceWorkflowId
visibility
canChangeVisibility
diff --git a/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflowsWithCurrentVersions.ts b/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflowsWithCurrentVersions.ts
index 270bd970c52..61d37098e89 100644
--- a/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflowsWithCurrentVersions.ts
+++ b/packages/twenty-front/src/modules/object-core/workflows/graphql/queries/getCoreWorkflowsWithCurrentVersions.ts
@@ -8,6 +8,7 @@ export const GET_CORE_WORKFLOWS_WITH_CURRENT_VERSIONS = gql`
workflow {
id
name
+ applicationId
statuses
lastPublishedCoreWorkflowVersionId
}
diff --git a/packages/twenty-front/src/modules/object-core/workflows/versions/utils/__tests__/invalidateCoreWorkflowVersions.test.ts b/packages/twenty-front/src/modules/object-core/workflows/versions/utils/__tests__/invalidateCoreWorkflowVersions.test.ts
index 28aa61b6165..9e46e7463b2 100644
--- a/packages/twenty-front/src/modules/object-core/workflows/versions/utils/__tests__/invalidateCoreWorkflowVersions.test.ts
+++ b/packages/twenty-front/src/modules/object-core/workflows/versions/utils/__tests__/invalidateCoreWorkflowVersions.test.ts
@@ -23,6 +23,7 @@ describe('invalidateCoreWorkflowVersions', () => {
data: {
coreWorkflow: {
id: operation.variables.coreWorkflowId,
+ applicationId: '23c5bdee-5cc3-42a4-8f90-8d89e1418851',
name,
statuses: ['DRAFT'],
lastPublishedCoreWorkflowVersionId: null,
diff --git a/packages/twenty-front/src/modules/object-metadata/utils/getEnabledAddressSubFields.ts b/packages/twenty-front/src/modules/object-metadata/utils/getEnabledAddressSubFields.ts
index dcc840fcd63..e5b6f354022 100644
--- a/packages/twenty-front/src/modules/object-metadata/utils/getEnabledAddressSubFields.ts
+++ b/packages/twenty-front/src/modules/object-metadata/utils/getEnabledAddressSubFields.ts
@@ -1,19 +1 @@
-import { DEFAULT_VISIBLE_ADDRESS_SUBFIELDS } from 'twenty-shared/constants';
-import {
- type AllowedAddressSubField,
- type FieldMetadataSettingsMapping,
- type FieldMetadataType,
-} from 'twenty-shared/types';
-import { isNonEmptyArray } from 'twenty-shared/utils';
-
-export const getEnabledAddressSubFields = (
- settings:
- | FieldMetadataSettingsMapping[FieldMetadataType.ADDRESS]
- | null
- | undefined,
-): readonly AllowedAddressSubField[] => {
- if (isNonEmptyArray(settings?.subFields)) {
- return settings.subFields;
- }
- return DEFAULT_VISIBLE_ADDRESS_SUBFIELDS;
-};
+export { getEnabledAddressSubFields } from 'twenty-shared/utils';
diff --git a/packages/twenty-front/src/modules/object-metadata/utils/getOrderByForFieldMetadataType.ts b/packages/twenty-front/src/modules/object-metadata/utils/getOrderByForFieldMetadataType.ts
index 4464602e5c2..b1dcefd4688 100644
--- a/packages/twenty-front/src/modules/object-metadata/utils/getOrderByForFieldMetadataType.ts
+++ b/packages/twenty-front/src/modules/object-metadata/utils/getOrderByForFieldMetadataType.ts
@@ -1,107 +1,13 @@
import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
import { type FieldMetadataItem } from '@/object-metadata/types/FieldMetadataItem';
import { getLabelIdentifierFieldMetadataItem } from '@/object-metadata/utils/getLabelIdentifierFieldMetadataItem';
-import { resolveAddressSortSubField } from '@/object-metadata/utils/resolveAddressSortSubField';
-import { resolvePrimaryFullNameSortSubField } from '@/object-metadata/utils/resolvePrimaryFullNameSortSubField';
-
-import {
- type FieldEmailsValue,
- type FieldLinksValue,
- type FieldPhonesValue,
-} from '@/object-record/record-field/ui/types/FieldMetadata';
import {
- type FieldMetadataSettingsMapping,
type OrderBy,
type RecordGqlOperationOrderBy,
} from 'twenty-shared/types';
-import { FieldMetadataType } from '~/generated-metadata/graphql';
+import { getOrderByForRelationField as computeRelationOrderBy } from 'twenty-shared/utils';
-export const getOrderByForFieldMetadataType = ({
- field,
- orderByDirection,
- primaryCompositeSubField,
-}: {
- field: Pick<FieldMetadataItem, 'id' | 'name' | 'type' | 'settings'>;
- orderByDirection: OrderBy | null | undefined;
- primaryCompositeSubField?: string | null;
-}): RecordGqlOperationOrderBy => {
- switch (field.type) {
- case FieldMetadataType.FULL_NAME: {
- const primarySubField = resolvePrimaryFullNameSortSubField({
- requestedPrimarySubField: primaryCompositeSubField,
- });
- const secondarySubField =
- primarySubField === 'firstName' ? 'lastName' : 'firstName';
- const direction = orderByDirection ?? 'AscNullsLast';
- return [
- { [field.name]: { [primarySubField]: direction } },
- { [field.name]: { [secondarySubField]: direction } },
- ];
- }
- case FieldMetadataType.ADDRESS: {
- const subField = resolveAddressSortSubField({
- settings: field.settings as
- | FieldMetadataSettingsMapping[FieldMetadataType.ADDRESS]
- | null
- | undefined,
- primaryCompositeSubField,
- });
- return [
- {
- [field.name]: {
- [subField]: orderByDirection ?? 'AscNullsLast',
- },
- },
- ];
- }
- case FieldMetadataType.CURRENCY:
- return [
- {
- [field.name]: {
- amountMicros: orderByDirection ?? 'AscNullsLast',
- },
- },
- ];
- case FieldMetadataType.ACTOR:
- return [
- {
- [field.name]: {
- name: orderByDirection ?? 'AscNullsLast',
- },
- },
- ];
- case FieldMetadataType.LINKS:
- return [
- {
- [field.name]: {
- primaryLinkUrl: orderByDirection ?? 'AscNullsLast',
- } satisfies { [key in keyof FieldLinksValue]?: OrderBy },
- },
- ];
- case FieldMetadataType.EMAILS:
- return [
- {
- [field.name]: {
- primaryEmail: orderByDirection ?? 'AscNullsLast',
- } satisfies { [key in keyof FieldEmailsValue]?: OrderBy },
- },
- ];
- case FieldMetadataType.PHONES:
- return [
- {
- [field.name]: {
- primaryPhoneNumber: orderByDirection ?? 'AscNullsLast',
- } satisfies { [key in keyof FieldPhonesValue]?: OrderBy },
- },
- ];
- default:
- return [
- {
- [field.name]: orderByDirection ?? 'AscNullsLast',
- },
- ];
- }
-};
+export { getOrderByForFieldMetadataType } from 'twenty-shared/utils';
export const getOrderByForRelationField = ({
field,
@@ -114,19 +20,11 @@ export const getOrderByForRelationField = ({
'fields' | 'labelIdentifierFieldMetadataId'
>;
orderByDirection: OrderBy;
-}): RecordGqlOperationOrderBy => {
- const labelIdentifierField = getLabelIdentifierFieldMetadataItem(
- relatedObjectMetadataItem,
- );
-
- if (!labelIdentifierField) {
- return [{ [`${field.name}Id`]: orderByDirection }];
- }
-
- const labelFieldOrderBy = getOrderByForFieldMetadataType({
- field: labelIdentifierField,
+}): RecordGqlOperationOrderBy =>
+ computeRelationOrderBy({
+ field,
+ labelIdentifierField: getLabelIdentifierFieldMetadataItem(
+ relatedObjectMetadataItem,
+ ),
orderByDirection,
});
-
- return labelFieldOrderBy.map((entry) => ({ [field.name]: entry }));
-};
diff --git a/packages/twenty-front/src/modules/object-metadata/utils/resolveAddressSortSubField.ts b/packages/twenty-front/src/modules/object-metadata/utils/resolveAddressSortSubField.ts
index be0552a0545..829736a1e5d 100644
--- a/packages/twenty-front/src/modules/object-metadata/utils/resolveAddressSortSubField.ts
+++ b/packages/twenty-front/src/modules/object-metadata/utils/resolveAddressSortSubField.ts
@@ -1,42 +1 @@
-import { getEnabledAddressSubFields } from '@/object-metadata/utils/getEnabledAddressSubFields';
-import {
- ALLOWED_ADDRESS_SUBFIELDS,
- type AllowedAddressSubField,
- type FieldMetadataSettingsMapping,
- type FieldMetadataType,
-} from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
-
-const DEFAULT_SUB_FIELD: AllowedAddressSubField = 'addressCity';
-
-const isAllowedAddressSubField = (
- value: string | null | undefined,
-): value is AllowedAddressSubField =>
- ALLOWED_ADDRESS_SUBFIELDS.includes(value as AllowedAddressSubField);
-
-export const resolveAddressSortSubField = ({
- settings,
- primaryCompositeSubField,
-}: {
- settings:
- | FieldMetadataSettingsMapping[FieldMetadataType.ADDRESS]
- | null
- | undefined;
- primaryCompositeSubField?: string | null;
-}): AllowedAddressSubField => {
- const enabledSubFields = getEnabledAddressSubFields(settings);
-
- if (
- isDefined(primaryCompositeSubField) &&
- isAllowedAddressSubField(primaryCompositeSubField) &&
- enabledSubFields.includes(primaryCompositeSubField)
- ) {
- return primaryCompositeSubField;
- }
-
- if (enabledSubFields.includes(DEFAULT_SUB_FIELD)) {
- return DEFAULT_SUB_FIELD;
- }
-
- return enabledSubFields[0] ?? DEFAULT_SUB_FIELD;
-};
+export { resolveAddressSortSubField } from 'twenty-shared/utils';
diff --git a/packages/twenty-front/src/modules/object-metadata/utils/resolvePrimaryFullNameSortSubField.ts b/packages/twenty-front/src/modules/object-metadata/utils/resolvePrimaryFullNameSortSubField.ts
index 956bcb2e8c9..9ec1cca0af0 100644
--- a/packages/twenty-front/src/modules/object-metadata/utils/resolvePrimaryFullNameSortSubField.ts
+++ b/packages/twenty-front/src/modules/object-metadata/utils/resolvePrimaryFullNameSortSubField.ts
@@ -1,26 +1 @@
-import { ALLOWED_FULL_NAME_SORT_SUBFIELDS } from 'twenty-shared/constants';
-import { type AllowedFullNameSortSubField } from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
-
-const DEFAULT_PRIMARY_SUB_FIELD: AllowedFullNameSortSubField = 'firstName';
-
-const isAllowedFullNameSortSubField = (
- value: string | null | undefined,
-): value is AllowedFullNameSortSubField =>
- ALLOWED_FULL_NAME_SORT_SUBFIELDS.includes(
- value as AllowedFullNameSortSubField,
- );
-
-export const resolvePrimaryFullNameSortSubField = ({
- requestedPrimarySubField,
-}: {
- requestedPrimarySubField?: string | null;
-} = {}): AllowedFullNameSortSubField => {
- if (
- isDefined(requestedPrimarySubField) &&
- isAllowedFullNameSortSubField(requestedPrimarySubField)
- ) {
- return requestedPrimarySubField;
- }
- return DEFAULT_PRIMARY_SUB_FIELD;
-};
+export { resolvePrimaryFullNameSortSubField } from 'twenty-shared/utils';
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
index 107bbe60548..fe8ce9e0123 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
@@ -34,6 +34,10 @@ export const SETTINGS_ADMIN_FEATURE_FLAG_METADATA: Partial<
label: msg`Prebuilt logic functions`,
description: msg`Run logic functions from prebuilt application bundles.`,
},
+ [FeatureFlagKey.IS_APPLICATION_WORKFLOWS_ENABLED]: {
+ label: msg`Application workflows`,
+ description: msg`Allow applications to install workflows and start new workflow runs.`,
+ },
[FeatureFlagKey.IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED]: {
label: msg`Workflow index page`,
description: msg`Use the dedicated workflow index page to browse workflows and their versions.`,
diff --git a/packages/twenty-front/src/pages/object-core/WorkflowCoreShowPage.tsx b/packages/twenty-front/src/pages/object-core/WorkflowCoreShowPage.tsx
index 43fb55bc4d3..c6b38ee6ff6 100644
--- a/packages/twenty-front/src/pages/object-core/WorkflowCoreShowPage.tsx
+++ b/packages/twenty-front/src/pages/object-core/WorkflowCoreShowPage.tsx
@@ -1,3 +1,4 @@
+import { useIsThirdPartyApplication } from '@/applications/hooks/useIsThirdPartyApplication';
import { CoreWorkflowEditor } from '@/object-core/workflows/components/CoreWorkflowEditor';
import { CoreObjectIdentifierBar } from '@/object-core/components/CoreObjectIdentifierBar';
import { CoreWorkflowToWorkspaceRedirect } from '@/object-core/workflows/components/CoreWorkflowToWorkspaceRedirect';
@@ -56,6 +57,9 @@ const CoreWorkflowShowContent = ({
useCoreWorkflowShowPageResource({
coreWorkflowId,
});
+ const isApplicationManaged = useIsThirdPartyApplication(
+ coreWorkflow?.applicationId,
+ );
const versions = useCoreWorkflowVersions(coreWorkflowId);
const { refetchCoreWorkflowVersions } = versions;
@@ -78,7 +82,8 @@ const CoreWorkflowShowContent = ({
const selectedVersion = isDefined(requestedVersionId)
? versions.coreWorkflowVersions.find(({ id }) => id === requestedVersionId)
: currentVersion;
- const isReadOnlyVersion = isDefined(requestedVersionId);
+ const isReadOnlyVersion =
+ isApplicationManaged || isDefined(requestedVersionId);
const { renameWorkflow } = useRenameCoreWorkflow({
coreWorkflowId,
currentName: record?.name,
@@ -112,7 +117,9 @@ const CoreWorkflowShowContent = ({
<Button
title={t`Retry`}
onClick={() => invalidateCoreWorkflowVersions(client)}
- />
+ >
+ {t`Retry`}
+ </Button>
</WorkspaceRouteUnavailable>
</>
);
@@ -155,7 +162,7 @@ const CoreWorkflowShowContent = ({
]}
actionButton={
<>
- {!isReadOnlyVersion && <RecordShowCommandMenu />}
+ {!isDefined(requestedVersionId) && <RecordShowCommandMenu />}
<SidePanelToggleButton />
</>
}
@@ -168,6 +175,7 @@ const CoreWorkflowShowContent = ({
name={record.name}
namePlaceholder={t`Untitled`}
onRename={renameWorkflow}
+ isReadOnly={isApplicationManaged}
/>
{isDefined(selectedVersion) ? (
<CoreWorkflowEditor
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/2-45-instance-command-fast-1790853315722-add-application-workflow-side-effects.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/2-45-instance-command-fast-1790853315722-add-application-workflow-side-effects.ts
new file mode 100644
index 00000000000..09218822ccb
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/2-45-instance-command-fast-1790853315722-add-application-workflow-side-effects.ts
@@ -0,0 +1,17 @@
+import { QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';
+
+@RegisteredInstanceCommand('2.45.0', 1790853315722)
+export class AddApplicationWorkflowSideEffectsFastInstanceCommand implements FastInstanceCommand {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query('ALTER TABLE "core"."workflow" ADD "versionDefinitionHash" text');
+ await queryRunner.query('ALTER TABLE "core"."workflowVersion" ADD "isSystemSideEffect" boolean NOT NULL DEFAULT false');
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query('ALTER TABLE "core"."workflowVersion" DROP COLUMN "isSystemSideEffect"');
+ await queryRunner.query('ALTER TABLE "core"."workflow" DROP COLUMN "versionDefinitionHash"');
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/2-45-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/2-45-upgrade-version-command.module.ts
index 21789bae4e0..c2b205d1218 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/2-45-upgrade-version-command.module.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/2-45-upgrade-version-command.module.ts
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { WorkspaceIteratorModule } from 'src/database/commands/command-runners/workspace-iterator.module';
import { RestrictExportRecordsToIndexPageCommand } from 'src/database/commands/upgrade-version-command/2-45/2-45-workspace-command-1790837443029-restrict-export-records-to-index-page.command';
+import { GateWorkflowCommandsOnRecordUpdatePermissionCommand } from 'src/database/commands/upgrade-version-command/2-45/2-45-workspace-command-1790853316722-gate-workflow-commands-on-record-update-permission.command';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration.module';
@@ -11,6 +12,9 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace
WorkspaceIteratorModule,
WorkspaceMigrationModule,
],
- providers: [RestrictExportRecordsToIndexPageCommand],
+ providers: [
+ RestrictExportRecordsToIndexPageCommand,
+ GateWorkflowCommandsOnRecordUpdatePermissionCommand,
+ ],
})
export class V2_45_UpgradeVersionCommandModule {}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/2-45-workspace-command-1790853316722-gate-workflow-commands-on-record-update-permission.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/2-45-workspace-command-1790853316722-gate-workflow-commands-on-record-update-permission.command.ts
new file mode 100644
index 00000000000..a6cb04607e2
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/2-45-workspace-command-1790853316722-gate-workflow-commands-on-record-update-permission.command.ts
@@ -0,0 +1,91 @@
+import { Command } from 'nest-commander';
+import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
+import { isNonEmptyArray } 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 { buildWorkflowCommandUpdatePermissionUpdates } from 'src/database/commands/upgrade-version-command/2-45/utils/build-workflow-command-update-permission-updates.util';
+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+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';
+
+@RegisteredWorkspaceCommand('2.45.0', 1790853316722)
+@Command({
+ name: 'upgrade:2-45:gate-workflow-commands-on-record-update-permission',
+ description:
+ 'Hide workflow definition commands on workflows the user cannot update, such as application workflows',
+})
+export class GateWorkflowCommandsOnRecordUpdatePermissionCommand extends ProvisionedWorkspaceCommandRunner {
+ constructor(
+ protected readonly workspaceIteratorService: WorkspaceIteratorService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,
+ ) {
+ super(workspaceIteratorService);
+ }
+
+ override async runOnWorkspace(args: RunOnWorkspaceArgs): Promise<void> {
+ await this.up(args);
+ }
+
+ async up(args: RunOnWorkspaceArgs): Promise<void> {
+ await this.syncAvailability(args, 'up');
+ }
+
+ async down(args: RunOnWorkspaceArgs): Promise<void> {
+ await this.syncAvailability(args, 'down');
+ }
+
+ private async syncAvailability(
+ { workspaceId, options }: RunOnWorkspaceArgs,
+ direction: 'up' | 'down',
+ ): Promise<void> {
+ const { flatCommandMenuItemMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatCommandMenuItemMaps',
+ ]);
+
+ const commandMenuItemsToUpdate =
+ buildWorkflowCommandUpdatePermissionUpdates({
+ flatCommandMenuItemsByUniversalIdentifier:
+ flatCommandMenuItemMaps.byUniversalIdentifier,
+ now: new Date().toISOString(),
+ direction,
+ });
+
+ if (!isNonEmptyArray(commandMenuItemsToUpdate)) {
+ return;
+ }
+
+ this.logger.log(
+ `${options.dryRun ? '[DRY RUN] ' : ''}Workspace ${workspaceId}: updating ${commandMenuItemsToUpdate.length} workflow command menu items`,
+ );
+
+ if (options.dryRun) {
+ return;
+ }
+
+ const result =
+ await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunLegacyWorkspaceMigration(
+ {
+ workspaceId,
+ isSystemBuild: true,
+ applicationUniversalIdentifier:
+ TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,
+ allFlatEntityOperationByMetadataName: {
+ commandMenuItem: {
+ flatEntityToCreate: [],
+ flatEntityToDelete: [],
+ flatEntityToUpdate: commandMenuItemsToUpdate,
+ },
+ },
+ },
+ );
+
+ if (result.status === 'fail') {
+ throw new WorkspaceMigrationBuilderException(result);
+ }
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/add-application-workflow-side-effects-upgrade-command-name.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/add-application-workflow-side-effects-upgrade-command-name.constant.ts
new file mode 100644
index 00000000000..db263ebb168
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/add-application-workflow-side-effects-upgrade-command-name.constant.ts
@@ -0,0 +1,2 @@
+export const ADD_APPLICATION_WORKFLOW_SIDE_EFFECTS_UPGRADE_COMMAND_NAME =
+ '2.45.0_AddApplicationWorkflowSideEffectsFastInstanceCommand_1790853315722';
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/utils/__tests__/build-workflow-command-update-permission-updates.util.spec.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/utils/__tests__/build-workflow-command-update-permission-updates.util.spec.ts
new file mode 100644
index 00000000000..68ba280ceab
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/utils/__tests__/build-workflow-command-update-permission-updates.util.spec.ts
@@ -0,0 +1,130 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { buildWorkflowCommandUpdatePermissionUpdates } from 'src/database/commands/upgrade-version-command/2-45/utils/build-workflow-command-update-permission-updates.util';
+import { type FlatCommandMenuItem } from 'src/engine/metadata-modules/flat-command-menu-item/types/flat-command-menu-item.type';
+import { computeTwentyStandardApplicationAllFlatEntityMaps } from 'src/engine/workspace-manager/twenty-standard-application/utils/twenty-standard-application-all-flat-entity-maps.constant';
+
+const NOW = '2026-09-30T12:00:00.000Z';
+const RECORD_UPDATE_PERMISSION_CONDITION =
+ ' and noneEquals(selectedRecords, "recordPermissions.canUpdate", false)';
+const WORKFLOW_COMMAND_UNIVERSAL_IDENTIFIERS = [
+ '57f21a06-a17a-47b1-a123-90d90dbdf0b7',
+ '91094438-b4c2-46ad-a23b-8af4b23ba514',
+ '1f3a3cab-161a-4775-af47-11be4d0bf411',
+ '26f98606-8b6e-42f2-bc97-2cfc4359bada',
+];
+
+const { allFlatEntityMaps } = computeTwentyStandardApplicationAllFlatEntityMaps(
+ {
+ now: '2026-09-27T12:00:00.000Z',
+ workspaceId: '20202020-1111-4111-8111-111111111111',
+ twentyStandardApplicationId: '20202020-2222-4222-8222-222222222222',
+ },
+);
+
+const getStandardItem = (universalIdentifier: string): FlatCommandMenuItem => {
+ const commandMenuItem =
+ allFlatEntityMaps.flatCommandMenuItemMaps.byUniversalIdentifier[
+ universalIdentifier
+ ];
+
+ if (!isDefined(commandMenuItem)) {
+ throw new Error(
+ `Standard command menu item ${universalIdentifier} missing`,
+ );
+ }
+
+ return commandMenuItem;
+};
+
+const withPreviousExpressions = () => {
+ return Object.fromEntries(
+ WORKFLOW_COMMAND_UNIVERSAL_IDENTIFIERS.map((universalIdentifier) => {
+ const standardItem = getStandardItem(universalIdentifier);
+
+ return [
+ universalIdentifier,
+ {
+ ...standardItem,
+ conditionalAvailabilityExpression:
+ standardItem.conditionalAvailabilityExpression?.replace(
+ RECORD_UPDATE_PERMISSION_CONDITION,
+ '',
+ ) ?? null,
+ },
+ ];
+ }),
+ );
+};
+
+describe('buildWorkflowCommandUpdatePermissionUpdates', () => {
+ it('moves the workflow commands to the current standard expressions', () => {
+ const updates = buildWorkflowCommandUpdatePermissionUpdates({
+ flatCommandMenuItemsByUniversalIdentifier: withPreviousExpressions(),
+ now: NOW,
+ direction: 'up',
+ });
+
+ expect(updates).toHaveLength(WORKFLOW_COMMAND_UNIVERSAL_IDENTIFIERS.length);
+ for (const update of updates) {
+ expect(update.conditionalAvailabilityExpression).toBe(
+ getStandardItem(update.universalIdentifier)
+ .conditionalAvailabilityExpression,
+ );
+ expect(update.updatedAt).toBe(NOW);
+ }
+ });
+
+ it('leaves customized expressions untouched', () => {
+ const items = withPreviousExpressions();
+ const [customizedUniversalIdentifier] =
+ WORKFLOW_COMMAND_UNIVERSAL_IDENTIFIERS;
+ const customized = items[customizedUniversalIdentifier];
+
+ if (!isDefined(customized)) {
+ throw new Error('Expected a workflow command');
+ }
+
+ items[customizedUniversalIdentifier] = {
+ ...customized,
+ conditionalAvailabilityExpression: 'numberOfSelectedRecords == 1',
+ };
+
+ const updates = buildWorkflowCommandUpdatePermissionUpdates({
+ flatCommandMenuItemsByUniversalIdentifier: items,
+ now: NOW,
+ direction: 'up',
+ });
+
+ expect(
+ updates.map(({ universalIdentifier }) => universalIdentifier),
+ ).not.toContain(customizedUniversalIdentifier);
+ expect(updates).toHaveLength(
+ WORKFLOW_COMMAND_UNIVERSAL_IDENTIFIERS.length - 1,
+ );
+ });
+
+ it('restores the previous expressions on down', () => {
+ const standardItems = Object.fromEntries(
+ WORKFLOW_COMMAND_UNIVERSAL_IDENTIFIERS.map((universalIdentifier) => [
+ universalIdentifier,
+ getStandardItem(universalIdentifier),
+ ]),
+ );
+ const previousItems = withPreviousExpressions();
+
+ const updates = buildWorkflowCommandUpdatePermissionUpdates({
+ flatCommandMenuItemsByUniversalIdentifier: standardItems,
+ now: NOW,
+ direction: 'down',
+ });
+
+ expect(updates).toHaveLength(WORKFLOW_COMMAND_UNIVERSAL_IDENTIFIERS.length);
+ for (const update of updates) {
+ expect(update.conditionalAvailabilityExpression).toBe(
+ previousItems[update.universalIdentifier]
+ ?.conditionalAvailabilityExpression,
+ );
+ }
+ });
+});
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/utils/build-workflow-command-update-permission-updates.util.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/utils/build-workflow-command-update-permission-updates.util.ts
new file mode 100644
index 00000000000..20d7182bfa3
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-45/utils/build-workflow-command-update-permission-updates.util.ts
@@ -0,0 +1,69 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatCommandMenuItem } from 'src/engine/metadata-modules/flat-command-menu-item/types/flat-command-menu-item.type';
+
+const RECORD_UPDATE_PERMISSION_CONDITION =
+ ' and noneEquals(selectedRecords, "recordPermissions.canUpdate", false)';
+
+const PREVIOUS_WORKFLOW_COMMAND_EXPRESSIONS = {
+ deactivateWorkflow: {
+ universalIdentifier: '57f21a06-a17a-47b1-a123-90d90dbdf0b7',
+ expression:
+ 'numberOfSelectedRecords == 1 and (everyEquals(selectedRecords, "currentVersion.status", "ACTIVE") or includesEvery(selectedRecords, "statuses", "ACTIVE")) and noneDefined(selectedRecords, "deletedAt")',
+ },
+ duplicateWorkflow: {
+ universalIdentifier: '91094438-b4c2-46ad-a23b-8af4b23ba514',
+ expression:
+ 'everyDefined(selectedRecords, "currentVersion") and noneDefined(selectedRecords, "deletedAt")',
+ },
+ tidyUpWorkflow: {
+ universalIdentifier: '1f3a3cab-161a-4775-af47-11be4d0bf411',
+ expression:
+ 'pageType == "RECORD_PAGE" and everyDefined(selectedRecords, "currentVersion.trigger") and everyDefined(selectedRecords, "currentVersion.steps") and every(selectedRecords, "currentVersion.steps.length") and noneDefined(selectedRecords, "deletedAt")',
+ },
+ toggleWorkflowVisibility: {
+ universalIdentifier: '26f98606-8b6e-42f2-bc97-2cfc4359bada',
+ expression:
+ 'numberOfSelectedRecords == 1 and everyEquals(selectedRecords, "visibility", "WORKSPACE") and every(selectedRecords, "canChangeVisibility") and noneDefined(selectedRecords, "deletedAt")',
+ },
+};
+
+export const buildWorkflowCommandUpdatePermissionUpdates = ({
+ flatCommandMenuItemsByUniversalIdentifier,
+ now,
+ direction,
+}: {
+ flatCommandMenuItemsByUniversalIdentifier: Record<
+ string,
+ FlatCommandMenuItem | undefined
+ >;
+ now: string;
+ direction: 'up' | 'down';
+}): FlatCommandMenuItem[] => {
+ return Object.values(PREVIOUS_WORKFLOW_COMMAND_EXPRESSIONS).flatMap(
+ ({ universalIdentifier, expression }) => {
+ const commandMenuItem =
+ flatCommandMenuItemsByUniversalIdentifier[universalIdentifier];
+ const nextExpression = `${expression}${RECORD_UPDATE_PERMISSION_CONDITION}`;
+ const [fromExpression, toExpression] =
+ direction === 'up'
+ ? [expression, nextExpression]
+ : [nextExpression, expression];
+
+ if (
+ !isDefined(commandMenuItem) ||
+ commandMenuItem.conditionalAvailabilityExpression !== fromExpression
+ ) {
+ return [];
+ }
+
+ return [
+ {
+ ...commandMenuItem,
+ conditionalAvailabilityExpression: toExpression,
+ updatedAt: now,
+ },
+ ];
+ },
+ );
+};
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
index 76c622c7dd2..ddcd5b52875 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
@@ -1,3 +1,4 @@
+import { AddApplicationWorkflowSideEffectsFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-45/2-45-instance-command-fast-1790853315722-add-application-workflow-side-effects';
// Auto-edited by generate:instance-command — do not edit manually
import { AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand } from 'src/database/commands/upgrade-version-command/1-21/1-21-instance-command-fast-1775129420309-add-view-field-group-id-index-on-view-field';
@@ -436,4 +437,5 @@ export const INSTANCE_COMMANDS = [
ReapplyUsageLimitPeriodReshapeFastInstanceCommand,
AddChatWidgetTypeFastInstanceCommand,
DropLegacyCampaignSendingCoreTablesFastInstanceCommand,
+ AddApplicationWorkflowSideEffectsFastInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
index 3552860ceeb..c5302a65157 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
@@ -6,6 +6,8 @@ import { FeatureFlagKey } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { ComputeApplicationManifestAllUniversalFlatEntityMapsService } from 'src/engine/core-modules/application/application-manifest/services/compute-application-manifest-all-universal-flat-entity-maps.service';
+import { addWorkflowManifestsToFlatEntityMapsOrThrow } from 'src/engine/core-modules/application/application-manifest/utils/add-workflow-manifests-to-flat-entity-maps-or-throw.util';
+import { preallocateWorkflowReferenceIds } from 'src/engine/core-modules/application/application-manifest/utils/preallocate-workflow-reference-ids.util';
import { buildAllFlatEntityOperationRecordByMetadataNameFromFromTo } from 'src/engine/core-modules/application/application-manifest/utils/build-all-flat-entity-operation-record-by-metadata-name-from-from-to.util';
import { buildFromToAllUniversalFlatEntityMaps } from 'src/engine/core-modules/application/application-manifest/utils/build-from-to-all-universal-flat-entity-maps.util';
import { getApplicationSubAllFlatEntityMaps } from 'src/engine/core-modules/application/application-manifest/utils/get-application-sub-all-flat-entity-maps.util';
@@ -214,6 +216,27 @@ export class ApplicationManifestMigrationService {
workspaceId,
});
+ const idByUniversalIdentifierByMetadataName =
+ (manifest.workflows ?? []).length > 0
+ ? preallocateWorkflowReferenceIds({
+ fromAllFlatEntityMaps,
+ toAllUniversalFlatEntityMaps,
+ })
+ : {};
+
+ addWorkflowManifestsToFlatEntityMapsOrThrow({
+ workflows: manifest.workflows ?? [],
+ ownerFlatApplication,
+ fromAllFlatEntityMaps,
+ toAllUniversalFlatEntityMaps,
+ existingAllFlatEntityMaps,
+ idByUniversalIdentifierByMetadataName,
+ isApplicationWorkflowsEnabled:
+ featureFlagsMap[FeatureFlagKey.IS_APPLICATION_WORKFLOWS_ENABLED],
+ inferDeletionFromMissingEntities,
+ now,
+ });
+
const allFlatEntityOperationRecordByMetadataName =
buildAllFlatEntityOperationRecordByMetadataNameFromFromTo({
fromAllFlatEntityMaps,
@@ -237,6 +260,7 @@ export class ApplicationManifestMigrationService {
isSystemBuild: false,
applicationUniversalIdentifier:
ownerFlatApplication.universalIdentifier,
+ idByUniversalIdentifierByMetadataName,
dryRun,
},
);
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.spec.ts
new file mode 100644
index 00000000000..53d6d32cca8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.spec.ts
@@ -0,0 +1,237 @@
+import {
+ getWorkflowVersionUniversalIdentifier,
+ type WorkflowManifest,
+} from 'twenty-shared/application';
+
+import { fromWorkflowManifestToUniversalFlatWorkflowOrThrow } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util';
+import { type FlatWorkflow } from 'src/engine/metadata-modules/flat-workflow/types/flat-workflow.type';
+import { type FlatWorkflowVersion } from 'src/engine/metadata-modules/flat-workflow-version/types/flat-workflow-version.type';
+
+const WORKFLOW_ID = '11111111-1111-4111-8111-111111111111';
+const TRIGGER_ID = '33333333-3333-4333-8333-333333333333';
+const STEP_ID = '44444444-4444-4444-8444-444444444444';
+const FUNCTION_ID = '55555555-5555-4555-8555-555555555555';
+const APPLICATION_ID = '66666666-6666-4666-8666-666666666666';
+const manifest: WorkflowManifest = {
+ universalIdentifier: WORKFLOW_ID,
+ name: 'Greeting',
+ version: {
+ trigger: {
+ universalIdentifier: TRIGGER_ID,
+ type: 'MANUAL',
+ nextStepIds: [STEP_ID],
+ },
+ steps: [
+ {
+ universalIdentifier: STEP_ID,
+ name: 'Greet',
+ type: 'LOGIC_FUNCTION',
+ logicFunctionUniversalIdentifier: FUNCTION_ID,
+ input: { greeting: 'Before' },
+ nextStepIds: [],
+ },
+ ],
+ },
+};
+const options = {
+ manifest,
+ applicationUniversalIdentifier: APPLICATION_ID,
+ now: '2026-09-25T10:00:00.000Z',
+ logicFunctionIdByUniversalIdentifier: new Map([
+ [FUNCTION_ID, '77777777-7777-4777-8777-777777777777'],
+ ]),
+};
+
+const convert = (
+ args: Parameters<
+ typeof fromWorkflowManifestToUniversalFlatWorkflowOrThrow
+ >[0],
+) => {
+ const workflow = fromWorkflowManifestToUniversalFlatWorkflowOrThrow(args);
+ const version = workflow.flatUniversalWorkflowVersion;
+ if (!version) {
+ throw new Error('Expected application version payload');
+ }
+ return { workflow, version };
+};
+
+describe('application workflow definitions', () => {
+ it('creates one active core version without workspace projections', () => {
+ const { workflow, version } = convert(options);
+ expect(workflow.lastPublishedCoreWorkflowVersionId).toBe(version.id);
+ expect(version.coreWorkflowId).toBe(workflow.id);
+ expect(workflow.workspaceWorkflowId).toBeNull();
+ expect(version.workspaceWorkflowVersionId).toBeNull();
+ expect(version.status).toBe('ACTIVE');
+ expect(version.steps?.[0].settings.input).toEqual({
+ logicFunctionId:
+ options.logicFunctionIdByUniversalIdentifier.get(FUNCTION_ID),
+ logicFunctionInput: { greeting: 'Before' },
+ });
+ });
+
+ it('updates the same version and keeps graph identity across updates', () => {
+ const before = convert(options);
+ const existingWorkflow: FlatWorkflow = {
+ ...before.workflow,
+ workspaceId: APPLICATION_ID,
+ applicationId: APPLICATION_ID,
+ };
+ const existingVersion: FlatWorkflowVersion = {
+ ...before.version,
+ workspaceId: APPLICATION_ID,
+ applicationId: APPLICATION_ID,
+ };
+ const changed = structuredClone(manifest);
+ const changedStep = changed.version.steps[0];
+ if (changedStep.type !== 'LOGIC_FUNCTION') {
+ throw new Error('Expected a function step');
+ }
+ changedStep.input.greeting = 'After';
+ const after = convert({
+ ...options,
+ manifest: changed,
+ existingWorkflow,
+ existingVersion,
+ });
+ expect(after.workflow.id).toBe(before.workflow.id);
+ expect(after.version.id).toBe(before.version.id);
+ expect(after.version.steps?.[0].id).toBe(before.version.steps?.[0].id);
+ expect(after.version.steps?.[0].settings.input).toMatchObject({
+ logicFunctionInput: { greeting: 'After' },
+ });
+ expect(before.version.steps?.[0].settings.input).toMatchObject({
+ logicFunctionInput: { greeting: 'Before' },
+ });
+ });
+
+ it('resolves the same definition to different workspace function IDs', () => {
+ const first = convert(options);
+ const second = convert({
+ ...options,
+ logicFunctionIdByUniversalIdentifier: new Map([
+ [FUNCTION_ID, '88888888-8888-4888-8888-888888888888'],
+ ]),
+ });
+ expect(first.version.steps?.[0].settings.input).not.toEqual(
+ second.version.steps?.[0].settings.input,
+ );
+ expect(first.version.universalIdentifier).toBe(
+ getWorkflowVersionUniversalIdentifier({
+ applicationUniversalIdentifier: APPLICATION_ID,
+ workflowUniversalIdentifier: WORKFLOW_ID,
+ }),
+ );
+ expect(second.version.universalIdentifier).toBe(
+ first.version.universalIdentifier,
+ );
+ expect(first.version.id).not.toBe(second.version.id);
+ });
+
+ it('refuses missing or non-exposed application functions', () => {
+ expect(() =>
+ convert({
+ ...options,
+ logicFunctionIdByUniversalIdentifier: new Map(),
+ }),
+ ).toThrow('missing application workflow action');
+ });
+
+ it('rejects an unsupported trigger on the server too', () => {
+ const invalid = structuredClone(manifest);
+ Object.assign(invalid.version.trigger, { type: 'WEBHOOK' });
+ expect(() =>
+ convert({
+ ...options,
+ manifest: invalid,
+ }),
+ ).toThrow();
+ });
+});
+
+const BRANCH_ID = '77777777-7777-4777-8777-777777777777';
+const BODY_ID = '88888888-8888-4888-8888-888888888888';
+const FIRST_STEP_ID = manifest.version.steps[0].universalIdentifier;
+
+const branchingWorkflow = (type: 'IF_ELSE' | 'ITERATOR'): WorkflowManifest => ({
+ ...manifest,
+ version: {
+ ...manifest.version,
+ steps: [
+ ...(type === 'IF_ELSE'
+ ? [
+ {
+ universalIdentifier: FIRST_STEP_ID,
+ name: 'Choose',
+ type: 'IF_ELSE' as const,
+ nextStepIds: [],
+ input: {
+ stepFilters: [],
+ stepFilterGroups: [],
+ branches: [
+ { id: 'first', nextStepIds: [BRANCH_ID] },
+ { id: 'otherwise', nextStepIds: [BODY_ID] },
+ ],
+ },
+ },
+ ]
+ : [
+ {
+ universalIdentifier: FIRST_STEP_ID,
+ name: 'Repeat',
+ type: 'ITERATOR' as const,
+ nextStepIds: [BRANCH_ID],
+ input: { items: ['one', 'two'], initialLoopStepIds: [BODY_ID] },
+ },
+ ]),
+ {
+ universalIdentifier: BRANCH_ID,
+ name: 'After',
+ type: 'EMPTY',
+ input: {},
+ nextStepIds: [],
+ },
+ {
+ universalIdentifier: BODY_ID,
+ name: 'Inside',
+ type: 'EMPTY',
+ input: {},
+ nextStepIds: type === 'ITERATOR' ? [FIRST_STEP_ID] : [],
+ },
+ ],
+ },
+});
+
+describe('application workflow action graphs', () => {
+ it.each(['IF_ELSE', 'ITERATOR'] as const)(
+ 'accepts steps reachable only through %s edges',
+ (type) => {
+ expect(() =>
+ convert({
+ ...options,
+ manifest: branchingWorkflow(type),
+ }),
+ ).not.toThrow();
+ },
+ );
+
+ it('validates each action input instead of accepting arbitrary configuration', () => {
+ const httpRequestManifest = structuredClone(manifest);
+ const httpRequestStep = {
+ universalIdentifier: STEP_ID,
+ name: 'Request',
+ type: 'HTTP_REQUEST' as const,
+ input: { url: 'https://example.com', method: 'GET' as const },
+ nextStepIds: [],
+ };
+ httpRequestManifest.version.steps = [httpRequestStep];
+ expect(() =>
+ convert({ ...options, manifest: httpRequestManifest }),
+ ).not.toThrow();
+
+ Object.assign(httpRequestStep.input, { method: 'BOGUS' });
+ expect(() =>
+ convert({ ...options, manifest: httpRequestManifest }),
+ ).toThrow();
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts
new file mode 100644
index 00000000000..1d9930e6d11
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts
@@ -0,0 +1,295 @@
+import { FieldMetadataType } from 'twenty-shared/types';
+import {
+ workflowStepManifestSchema,
+ type WorkflowStepManifest,
+} from 'twenty-shared/application';
+import { WorkflowActionType } from 'twenty-shared/workflow';
+
+import { fromWorkflowStepManifestToActionOrThrow } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util';
+
+const STEP_ID = '11111111-1111-4111-8111-111111111111';
+const REFERENCE_ID = '22222222-2222-4222-8222-222222222222';
+const FIELD_ID = '33333333-3333-4333-8333-333333333333';
+const LOCAL_ID = '44444444-4444-4444-8444-444444444444';
+const references = {
+ logicFunctionIdByUniversalIdentifier: new Map([[REFERENCE_ID, LOCAL_ID]]),
+ agentIdByUniversalIdentifier: new Map([[REFERENCE_ID, LOCAL_ID]]),
+ objectByUniversalIdentifier: new Map([
+ [REFERENCE_ID, { nameSingular: 'company' }],
+ ]),
+ fieldByUniversalIdentifier: new Map([
+ [
+ 'name-field',
+ {
+ id: 'name-id',
+ name: 'name',
+ objectUniversalIdentifier: REFERENCE_ID,
+ type: FieldMetadataType.TEXT,
+ settings: null,
+ relationTargetObjectMetadataUniversalIdentifier: null,
+ },
+ ],
+ [
+ FIELD_ID,
+ {
+ id: LOCAL_ID,
+ name: 'owner',
+ objectUniversalIdentifier: REFERENCE_ID,
+ type: FieldMetadataType.TEXT,
+ settings: null,
+ relationTargetObjectMetadataUniversalIdentifier: null,
+ },
+ ],
+ ]),
+};
+const record = {
+ objectUniversalIdentifier: REFERENCE_ID,
+ objectRecord: { name: 'Company' },
+};
+const email = {
+ connectedAccountId: '{{trigger.accountId}}',
+ recipients: { to: '[email protected]' },
+};
+const filters = { stepFilterGroups: [], stepFilters: [] };
+const inputs = {
+ LOGIC_FUNCTION: { value: 'Hello' },
+ CREATE_RECORD: record,
+ UPDATE_RECORD: {
+ ...record,
+ objectRecordId: '{{trigger.recordId}}',
+ fieldsToUpdate: ['name'],
+ },
+ UPSERT_RECORD: record,
+ DELETE_RECORD: {
+ objectUniversalIdentifier: REFERENCE_ID,
+ objectRecordId: '{{trigger.recordId}}',
+ },
+ FIND_RECORDS: {
+ objectUniversalIdentifier: REFERENCE_ID,
+ filter: {
+ recordFilters: [
+ {
+ fieldMetadataUniversalIdentifier: FIELD_ID,
+ operand: 'Is',
+ value: 'x',
+ },
+ ],
+ },
+ orderBy: {
+ recordSorts: [
+ { fieldMetadataUniversalIdentifier: FIELD_ID, direction: 'ASC' },
+ ],
+ },
+ },
+ PICK_RECORD: {
+ objectUniversalIdentifier: REFERENCE_ID,
+ recordIds: ['{{trigger.recordId}}'],
+ strategy: 'LOAD_BALANCED',
+ loadBalance: {
+ objectUniversalIdentifier: REFERENCE_ID,
+ fieldUniversalIdentifier: FIELD_ID,
+ },
+ },
+ SEND_EMAIL: email,
+ DRAFT_EMAIL: email,
+ CREATE_CALENDAR_EVENT: {
+ connectedAccountId: '{{trigger.accountId}}',
+ title: 'Meeting',
+ startsAt: '2026-10-01T10:00:00Z',
+ endsAt: '2026-10-01T11:00:00Z',
+ isFullDay: false,
+ sendInvitations: false,
+ addConferencing: false,
+ },
+ FORM: [
+ {
+ id: FIELD_ID,
+ name: 'company',
+ label: 'Company',
+ type: 'RECORD',
+ settings: { objectUniversalIdentifier: REFERENCE_ID },
+ },
+ ],
+ HTTP_REQUEST: {
+ method: 'POST',
+ url: 'https://example.com',
+ body: '{{trigger.body}}',
+ },
+ AI_AGENT: {
+ agentUniversalIdentifier: REFERENCE_ID,
+ prompt: 'Summarize {{trigger.text}}',
+ },
+ CLASSIFY: { state: '{{trigger.text}}', questions: [] },
+ FILTER: filters,
+ IF_ELSE: {
+ ...filters,
+ branches: [{ id: 'otherwise', nextStepIds: [FIELD_ID] }],
+ },
+ ITERATOR: { items: '{{trigger.items}}', initialLoopStepIds: [FIELD_ID] },
+ DELAY: { delayType: 'DURATION', duration: { seconds: 1 } },
+ EMPTY: {},
+} satisfies Record<WorkflowStepManifest['type'], unknown>;
+
+const stepFor = (type: WorkflowStepManifest['type']) =>
+ workflowStepManifestSchema.parse({
+ universalIdentifier: STEP_ID,
+ name: type,
+ type,
+ input: inputs[type],
+ nextStepIds: [],
+ ...(type === 'LOGIC_FUNCTION'
+ ? { logicFunctionUniversalIdentifier: REFERENCE_ID }
+ : {}),
+ });
+
+const convert = (type: WorkflowStepManifest['type']) =>
+ fromWorkflowStepManifestToActionOrThrow({
+ step: stepFor(type),
+ index: 0,
+ references,
+ });
+
+describe('application workflow actions', () => {
+ it('derives a nested function output schema from an expected result', () => {
+ const step = stepFor(WorkflowActionType.LOGIC_FUNCTION);
+ step.expectedOutputSchema = { company: { name: 'Example' }, count: 2 };
+ const result = fromWorkflowStepManifestToActionOrThrow({
+ step,
+ index: 0,
+ references,
+ });
+ expect(result.settings.outputSchema).toMatchObject({
+ company: { isLeaf: false, value: { name: { type: 'string' } } },
+ count: { isLeaf: true, type: 'number' },
+ });
+ });
+
+ it('uses the declared function output schema without running the function', () => {
+ const outputSchema = {
+ greeting: {
+ isLeaf: true as const,
+ type: 'string' as const,
+ label: 'Greeting',
+ value: null,
+ },
+ };
+ const result = fromWorkflowStepManifestToActionOrThrow({
+ step: stepFor(WorkflowActionType.LOGIC_FUNCTION),
+ index: 0,
+ references: {
+ ...references,
+ logicFunctionOutputSchemaByUniversalIdentifier: new Map([
+ [REFERENCE_ID, outputSchema],
+ ]),
+ },
+ });
+ expect(result.settings.outputSchema).toEqual(outputSchema);
+ expect(result.settings.outputSchema).not.toBe(outputSchema);
+ });
+
+ it.each(
+ Object.values(WorkflowActionType).filter(
+ (type) => type !== WorkflowActionType.CODE,
+ ),
+ )('converts %s to its runtime action', (type) => {
+ expect(convert(type)).toMatchObject({ id: STEP_ID, type, valid: true });
+ });
+
+ it('resolves functions, agents, objects and filter fields', () => {
+ expect(convert(WorkflowActionType.LOGIC_FUNCTION).settings.input).toEqual({
+ logicFunctionId: LOCAL_ID,
+ logicFunctionInput: inputs.LOGIC_FUNCTION,
+ });
+ expect(convert(WorkflowActionType.AI_AGENT).settings.input).toEqual({
+ agentId: LOCAL_ID,
+ prompt: inputs.AI_AGENT.prompt,
+ });
+ expect(convert(WorkflowActionType.CREATE_RECORD).settings.input).toEqual({
+ objectName: 'company',
+ objectRecord: { name: 'Company' },
+ });
+ expect(
+ convert(WorkflowActionType.FIND_RECORDS).settings.input,
+ ).toMatchObject({
+ objectName: 'company',
+ filter: {
+ recordFilters: [
+ { fieldMetadataId: LOCAL_ID, operand: 'Is', value: 'x' },
+ ],
+ },
+ orderBy: {
+ recordSorts: [{ fieldMetadataId: LOCAL_ID, direction: 'ASC' }],
+ gqlOperationOrderBy: [{ owner: 'AscNullsLast' }],
+ },
+ });
+ expect(
+ convert(WorkflowActionType.PICK_RECORD).settings.input,
+ ).toMatchObject({
+ loadBalance: { objectNameSingular: 'company', fieldName: 'owner' },
+ });
+ expect(convert(WorkflowActionType.FORM).settings.input).toMatchObject([
+ { settings: { objectName: 'company' } },
+ ]);
+ });
+
+ it('rejects unavailable metadata and fields from another object', () => {
+ expect(() =>
+ fromWorkflowStepManifestToActionOrThrow({
+ step: stepFor(WorkflowActionType.AI_AGENT),
+ index: 0,
+ references: { ...references, agentIdByUniversalIdentifier: new Map() },
+ }),
+ ).toThrow('missing application agent');
+ expect(() =>
+ fromWorkflowStepManifestToActionOrThrow({
+ step: stepFor(WorkflowActionType.FIND_RECORDS),
+ index: 0,
+ references: {
+ ...references,
+ fieldByUniversalIdentifier: new Map([
+ [
+ FIELD_ID,
+ {
+ id: LOCAL_ID,
+ name: 'owner',
+ objectUniversalIdentifier: LOCAL_ID,
+ type: FieldMetadataType.TEXT,
+ settings: null,
+ relationTargetObjectMetadataUniversalIdentifier: null,
+ },
+ ],
+ ]),
+ },
+ }),
+ ).toThrow('does not belong');
+ });
+
+ it('preserves branches, loop entries, outputs and error handling', () => {
+ expect(convert(WorkflowActionType.IF_ELSE).settings.input).toEqual(
+ inputs.IF_ELSE,
+ );
+ expect(convert(WorkflowActionType.ITERATOR).settings.input).toEqual(
+ inputs.ITERATOR,
+ );
+ const step = {
+ ...stepFor(WorkflowActionType.HTTP_REQUEST),
+ outputSchema: { response: { type: 'string' } },
+ expectedOutputSchema: { ok: true },
+ errorHandlingOptions: {
+ retryOnFailure: { value: 2 },
+ continueOnFailure: { value: true },
+ },
+ };
+ const action = fromWorkflowStepManifestToActionOrThrow({
+ step,
+ index: 0,
+ references,
+ });
+ expect(action.settings).toMatchObject({
+ outputSchema: step.outputSchema,
+ expectedOutputSchema: step.expectedOutputSchema,
+ errorHandlingOptions: step.errorHandlingOptions,
+ });
+ expect(action.settings.outputSchema).not.toBe(step.outputSchema);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.ts
new file mode 100644
index 00000000000..8b145577c0e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util.ts
@@ -0,0 +1,110 @@
+import { createHash } from 'crypto';
+import { z } from 'zod';
+import { fromWorkflowStepManifestToActionOrThrow } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util';
+import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
+import { msg } from '@lingui/core/macro';
+import { isDefined } from 'twenty-shared/utils';
+import {
+ ApplicationException,
+ ApplicationExceptionCode,
+} from 'src/engine/core-modules/application/application.exception';
+import {
+ getWorkflowVersionUniversalIdentifier,
+ type WorkflowManifest,
+ workflowManifestSchema,
+} from 'twenty-shared/application';
+import { WorkflowVisibility } from 'twenty-shared/types';
+import { v4 } from 'uuid';
+
+import { WorkflowVersionStatus } from 'src/engine/core-modules/workflow/entities/workflow-version.entity';
+import { type FlatWorkflow } from 'src/engine/metadata-modules/flat-workflow/types/flat-workflow.type';
+import { type FlatWorkflowVersion } from 'src/engine/metadata-modules/flat-workflow-version/types/flat-workflow-version.type';
+import {
+ type WorkflowManualTrigger,
+ WorkflowTriggerType,
+} from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';
+import { type UniversalFlatWorkflow } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-workflow.type';
+
+export const fromWorkflowManifestToUniversalFlatWorkflowOrThrow = ({
+ manifest,
+ applicationUniversalIdentifier,
+ existingWorkflow,
+ existingVersion,
+ now,
+ ...references
+}: {
+ manifest: WorkflowManifest;
+ applicationUniversalIdentifier: string;
+ existingWorkflow?: FlatWorkflow;
+ existingVersion?: FlatWorkflowVersion;
+ now: string;
+} & WorkflowManifestReferences): UniversalFlatWorkflow & { id: string } => {
+ const parsed = z
+ .strictObject(workflowManifestSchema.shape)
+ .safeParse(manifest);
+ if (!parsed.success) {
+ throw new ApplicationException(
+ `Invalid workflow definition: ${parsed.error.message}`,
+ ApplicationExceptionCode.INVALID_INPUT,
+ { userFriendlyMessage: msg`Invalid application workflow definition.` },
+ );
+ }
+ const definition = parsed.data;
+ if (isDefined(existingWorkflow?.workspaceWorkflowId)) {
+ throw new ApplicationException(
+ 'Workspace workflows cannot be adopted by an application',
+ ApplicationExceptionCode.INVALID_INPUT,
+ {
+ userFriendlyMessage: msg`Workspace workflows cannot be adopted by an application.`,
+ },
+ );
+ }
+ const workflowId = existingWorkflow?.id ?? v4();
+ const versionId = existingVersion?.id ?? v4();
+ const versionUniversalIdentifier = getWorkflowVersionUniversalIdentifier({
+ applicationUniversalIdentifier,
+ workflowUniversalIdentifier: definition.universalIdentifier,
+ });
+
+ const steps = definition.version.steps.map((step, index) =>
+ fromWorkflowStepManifestToActionOrThrow({ step, index, references }),
+ );
+
+ const trigger = {
+ ...definition.version.trigger,
+ name: 'Manual trigger',
+ type: WorkflowTriggerType.MANUAL,
+ position: { x: 0, y: 0 },
+ settings: { outputSchema: {} },
+ } satisfies WorkflowManualTrigger;
+ return {
+ id: workflowId,
+ universalIdentifier: definition.universalIdentifier,
+ applicationUniversalIdentifier,
+ name: definition.name,
+ visibility: WorkflowVisibility.WORKSPACE,
+ createdByUserWorkspaceId: null,
+ workspaceWorkflowId: null,
+ lastPublishedVersionId: null,
+ lastPublishedCoreWorkflowVersionId: versionId,
+ createdAt: existingWorkflow?.createdAt ?? now,
+ updatedAt: now,
+ versionDefinitionHash: createHash('sha256')
+ .update(JSON.stringify({ trigger, steps }))
+ .digest('hex'),
+ flatUniversalWorkflowVersion: {
+ id: versionId,
+ universalIdentifier: versionUniversalIdentifier,
+ applicationUniversalIdentifier,
+ coreWorkflowId: workflowId,
+ workflowId: null,
+ workspaceWorkflowVersionId: null,
+ isSystemSideEffect: true,
+ status: WorkflowVersionStatus.ACTIVE,
+ triggers: [trigger],
+ steps,
+ createdAt: existingVersion?.createdAt ?? now,
+ updatedAt: now,
+ },
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts
new file mode 100644
index 00000000000..70b5eaf9881
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts
@@ -0,0 +1,247 @@
+import { computeWorkflowManifestOutputSchema } from 'src/engine/core-modules/application/application-manifest/utils/compute-workflow-manifest-output-schema.util';
+import { computeWorkflowManifestOrderBy } from 'src/engine/core-modules/application/application-manifest/utils/compute-workflow-manifest-order-by.util';
+import { msg } from '@lingui/core/macro';
+import { type WorkflowStepManifest } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+import { workflowActionSchema } from 'twenty-shared/workflow';
+
+import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
+import {
+ ApplicationException,
+ ApplicationExceptionCode,
+} from 'src/engine/core-modules/application/application.exception';
+import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+
+export const fromWorkflowStepManifestToActionOrThrow = ({
+ step,
+ index,
+ references,
+}: {
+ step: WorkflowStepManifest;
+ index: number;
+ references: WorkflowManifestReferences;
+}): WorkflowAction => {
+ const resolve = <T>(
+ map: ReadonlyMap<string, T> | undefined,
+ identifier: string,
+ kind: string,
+ ): T => {
+ const value = map?.get(identifier);
+ if (!isDefined(value)) {
+ throw new ApplicationException(
+ `Workflow step ${step.name}: missing ${kind} ${identifier}`,
+ ApplicationExceptionCode.INVALID_INPUT,
+ {
+ userFriendlyMessage: msg`The workflow references metadata that is not available to this application.`,
+ },
+ );
+ }
+ return value;
+ };
+ const objectName = (identifier: string) =>
+ resolve(references.objectByUniversalIdentifier, identifier, 'object')
+ .nameSingular;
+ const field = (identifier: string, objectUniversalIdentifier?: string) => {
+ const resolved = resolve(
+ references.fieldByUniversalIdentifier,
+ identifier,
+ 'field',
+ );
+ if (
+ isDefined(objectUniversalIdentifier) &&
+ resolved.objectUniversalIdentifier !== objectUniversalIdentifier
+ ) {
+ throw new ApplicationException(
+ 'Workflow field does not belong to the referenced object',
+ ApplicationExceptionCode.INVALID_INPUT,
+ {
+ userFriendlyMessage: msg`The workflow field does not belong to the referenced object.`,
+ },
+ );
+ }
+ return resolved;
+ };
+ const fieldReference = <
+ T extends { fieldMetadataUniversalIdentifier?: string },
+ >(
+ reference: T,
+ objectUniversalIdentifier?: string,
+ ) => {
+ const { fieldMetadataUniversalIdentifier, ...rest } = reference;
+ return {
+ ...rest,
+ ...(isDefined(fieldMetadataUniversalIdentifier)
+ ? {
+ fieldMetadataId: field(
+ fieldMetadataUniversalIdentifier,
+ objectUniversalIdentifier,
+ ).id,
+ }
+ : {}),
+ };
+ };
+ let input: unknown;
+ switch (step.type) {
+ case 'LOGIC_FUNCTION':
+ input = {
+ logicFunctionId: resolve(
+ references.logicFunctionIdByUniversalIdentifier,
+ step.logicFunctionUniversalIdentifier,
+ 'application workflow action',
+ ),
+ logicFunctionInput: step.input,
+ };
+ break;
+ case 'AI_AGENT': {
+ const { agentUniversalIdentifier, ...rest } = step.input;
+ input = {
+ ...rest,
+ ...(isDefined(agentUniversalIdentifier)
+ ? {
+ agentId: resolve(
+ references.agentIdByUniversalIdentifier,
+ agentUniversalIdentifier,
+ 'application agent',
+ ),
+ }
+ : {}),
+ };
+ break;
+ }
+ case 'CREATE_RECORD':
+ case 'UPDATE_RECORD':
+ case 'UPSERT_RECORD':
+ case 'DELETE_RECORD': {
+ const { objectUniversalIdentifier, ...rest } = step.input;
+ input = { ...rest, objectName: objectName(objectUniversalIdentifier) };
+ break;
+ }
+ case 'FIND_RECORDS': {
+ const { objectUniversalIdentifier, filter, orderBy, ...rest } =
+ step.input;
+ input = {
+ ...rest,
+ objectName: objectName(objectUniversalIdentifier),
+ ...(isDefined(filter)
+ ? {
+ filter: {
+ ...filter,
+ ...(isDefined(filter.recordFilters)
+ ? {
+ recordFilters: filter.recordFilters.map((reference) =>
+ fieldReference(reference, objectUniversalIdentifier),
+ ),
+ }
+ : {}),
+ },
+ }
+ : {}),
+ ...(isDefined(orderBy)
+ ? {
+ orderBy: {
+ ...orderBy,
+ ...(isDefined(orderBy.recordSorts)
+ ? {
+ gqlOperationOrderBy: orderBy.recordSorts.flatMap(
+ (reference) =>
+ computeWorkflowManifestOrderBy({
+ field: field(
+ reference.fieldMetadataUniversalIdentifier,
+ objectUniversalIdentifier,
+ ),
+ direction: reference.direction,
+ subFieldName: reference.subFieldName,
+ references,
+ }),
+ ),
+ recordSorts: orderBy.recordSorts.map((reference) =>
+ fieldReference(reference, objectUniversalIdentifier),
+ ),
+ }
+ : {}),
+ },
+ }
+ : {}),
+ };
+ break;
+ }
+ case 'PICK_RECORD': {
+ const { objectUniversalIdentifier, loadBalance, ...rest } = step.input;
+ input = {
+ ...rest,
+ objectName: objectName(objectUniversalIdentifier),
+ ...(isDefined(loadBalance)
+ ? {
+ loadBalance: {
+ objectNameSingular: objectName(
+ loadBalance.objectUniversalIdentifier,
+ ),
+ fieldName: field(
+ loadBalance.fieldUniversalIdentifier,
+ loadBalance.objectUniversalIdentifier,
+ ).name,
+ },
+ }
+ : {}),
+ };
+ break;
+ }
+ case 'FORM':
+ input = step.input.map((formField) => {
+ if (formField.type !== 'RECORD') {
+ return formField;
+ }
+ const { objectUniversalIdentifier, ...settings } =
+ formField.settings ?? {};
+ if (typeof objectUniversalIdentifier !== 'string') {
+ throw new ApplicationException(
+ 'Record picker fields require an object universal identifier',
+ ApplicationExceptionCode.INVALID_INPUT,
+ {
+ userFriendlyMessage: msg`The workflow record picker must reference an object.`,
+ },
+ );
+ }
+ return {
+ ...formField,
+ settings: {
+ ...settings,
+ objectName: objectName(objectUniversalIdentifier),
+ },
+ };
+ });
+ break;
+ case 'FILTER':
+ case 'IF_ELSE':
+ input = {
+ ...step.input,
+ stepFilters: step.input.stepFilters.map((reference) =>
+ fieldReference(reference),
+ ),
+ };
+ break;
+ default:
+ input = step.input;
+ }
+ return workflowActionSchema.parse({
+ id: step.universalIdentifier,
+ name: step.name,
+ type: step.type,
+ valid: true,
+ nextStepIds: step.nextStepIds,
+ position: step.position ?? { x: 0, y: (index + 1) * 180 },
+ settings: {
+ input: structuredClone(input),
+ outputSchema: structuredClone(
+ computeWorkflowManifestOutputSchema({ step, references }),
+ ),
+ ...(isDefined(step.expectedOutputSchema)
+ ? { expectedOutputSchema: structuredClone(step.expectedOutputSchema) }
+ : {}),
+ errorHandlingOptions: step.errorHandlingOptions ?? {
+ retryOnFailure: { value: 0 },
+ continueOnFailure: { value: false },
+ },
+ },
+ }) as WorkflowAction;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type.ts
new file mode 100644
index 00000000000..b5d82a160fe
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type.ts
@@ -0,0 +1,47 @@
+import { type BaseOutputSchemaV2 } from 'twenty-shared/workflow';
+import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+
+export type WorkflowManifestObjectReference = Pick<
+ FlatObjectMetadata,
+ 'nameSingular'
+> &
+ Partial<
+ Pick<
+ FlatObjectMetadata,
+ 'labelIdentifierFieldMetadataUniversalIdentifier' | 'namePlural'
+ >
+ >;
+
+export type WorkflowManifestFieldReference = {
+ objectUniversalIdentifier: string;
+} & Pick<
+ FlatFieldMetadata,
+ | 'id'
+ | 'name'
+ | 'type'
+ | 'settings'
+ | 'relationTargetObjectMetadataUniversalIdentifier'
+> &
+ Partial<Pick<FlatFieldMetadata, 'universalSettings'>>;
+
+export type WorkflowManifestReferences = {
+ logicFunctionOutputSchemaByUniversalIdentifier?: ReadonlyMap<
+ string,
+ BaseOutputSchemaV2
+ >;
+ agentOutputSchemaByUniversalIdentifier?: ReadonlyMap<
+ string,
+ BaseOutputSchemaV2
+ >;
+ logicFunctionIdByUniversalIdentifier: ReadonlyMap<string, string>;
+ agentIdByUniversalIdentifier?: ReadonlyMap<string, string>;
+ objectByUniversalIdentifier?: ReadonlyMap<
+ string,
+ WorkflowManifestObjectReference
+ >;
+ fieldByUniversalIdentifier?: ReadonlyMap<
+ string,
+ WorkflowManifestFieldReference
+ >;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/add-workflow-manifests-to-flat-entity-maps-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/add-workflow-manifests-to-flat-entity-maps-or-throw.util.spec.ts
new file mode 100644
index 00000000000..8947577b6f8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/add-workflow-manifests-to-flat-entity-maps-or-throw.util.spec.ts
@@ -0,0 +1,186 @@
+import { type UniversalFlatWorkflow } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-workflow.type';
+import { type FlatWorkflowVersion } from 'src/engine/metadata-modules/flat-workflow-version/types/flat-workflow-version.type';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+import { addWorkflowManifestsToFlatEntityMapsOrThrow } from 'src/engine/core-modules/application/application-manifest/utils/add-workflow-manifests-to-flat-entity-maps-or-throw.util';
+import { isDefined } from 'twenty-shared/utils';
+
+import { createEmptyAllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-all-flat-entity-maps.constant';
+import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
+
+const MANIFEST = buildBaseManifest({
+ appId: '11111111-1111-4111-8111-111111111111',
+ roleId: '22222222-2222-4222-8222-222222222222',
+ overrides: {
+ workflows: [
+ {
+ universalIdentifier: '33333333-3333-4333-8333-333333333333',
+ name: 'Workflow',
+ version: {
+ trigger: {
+ universalIdentifier: '55555555-5555-4555-8555-555555555555',
+ type: 'MANUAL',
+ nextStepIds: ['66666666-6666-4666-8666-666666666666'],
+ },
+ steps: [
+ {
+ universalIdentifier: '66666666-6666-4666-8666-666666666666',
+ type: 'EMPTY',
+ name: 'Finish',
+ input: {},
+ nextStepIds: [],
+ },
+ ],
+ },
+ },
+ ],
+ },
+});
+
+describe('application workflow installation gate', () => {
+ it.each([undefined, false])(
+ 'rejects workflows when the flag is %s',
+ (isApplicationWorkflowsEnabled) => {
+ expect(() =>
+ addWorkflowManifestsToFlatEntityMapsOrThrow({
+ workflows: MANIFEST.workflows ?? [],
+ ownerFlatApplication: {
+ id: MANIFEST.application.universalIdentifier,
+ universalIdentifier: MANIFEST.application.universalIdentifier,
+ },
+ fromAllFlatEntityMaps: createEmptyAllFlatEntityMaps(),
+ toAllUniversalFlatEntityMaps: createEmptyAllFlatEntityMaps(),
+ existingAllFlatEntityMaps: createEmptyAllFlatEntityMaps(),
+ idByUniversalIdentifierByMetadataName: {},
+ isApplicationWorkflowsEnabled,
+ inferDeletionFromMissingEntities: true,
+ now: '2026-09-28T00:00:00.000Z',
+ }),
+ ).toThrow('Application workflows are not enabled');
+ },
+ );
+});
+
+const compute = ({
+ workflows = MANIFEST.workflows ?? [],
+ fromAllFlatEntityMaps = createEmptyAllFlatEntityMaps(),
+ inferDeletionFromMissingEntities = true,
+} = {}) => {
+ for (const workflow of Object.values(
+ fromAllFlatEntityMaps.flatWorkflowMaps.byUniversalIdentifier,
+ )) {
+ const version = (workflow as UniversalFlatWorkflow | undefined)
+ ?.flatUniversalWorkflowVersion;
+ if (isDefined(version)) {
+ fromAllFlatEntityMaps.flatWorkflowVersionMaps.byUniversalIdentifier[
+ version.universalIdentifier
+ ] = version as FlatWorkflowVersion;
+ }
+ }
+ const toAllUniversalFlatEntityMaps = createEmptyAllFlatEntityMaps();
+
+ addWorkflowManifestsToFlatEntityMapsOrThrow({
+ workflows,
+ ownerFlatApplication: {
+ id: MANIFEST.application.universalIdentifier,
+ universalIdentifier: MANIFEST.application.universalIdentifier,
+ },
+ fromAllFlatEntityMaps,
+ toAllUniversalFlatEntityMaps,
+ existingAllFlatEntityMaps: fromAllFlatEntityMaps,
+ idByUniversalIdentifierByMetadataName: {},
+ isApplicationWorkflowsEnabled: true,
+ inferDeletionFromMissingEntities,
+ now: '2026-09-28T00:00:00.000Z',
+ });
+
+ return toAllUniversalFlatEntityMaps;
+};
+
+describe('application workflow manifest updates', () => {
+ it('preserves workflow and version identity when updating the definition', () => {
+ const before = compute();
+ const workflows = structuredClone(MANIFEST.workflows ?? []);
+ const workflow = workflows[0];
+ if (!isDefined(workflow)) {
+ throw new Error('Expected workflow');
+ }
+ workflow.name = 'Updated';
+
+ const after = compute({ workflows, fromAllFlatEntityMaps: before });
+ expect(
+ after.flatWorkflowMaps.byUniversalIdentifier[
+ workflow.universalIdentifier
+ ],
+ ).toMatchObject({
+ id: before.flatWorkflowMaps.byUniversalIdentifier[
+ workflow.universalIdentifier
+ ]?.id,
+ name: 'Updated',
+ });
+ expect(after.flatWorkflowVersionMaps.byUniversalIdentifier).toEqual({});
+ expect(
+ (
+ after.flatWorkflowMaps.byUniversalIdentifier[
+ workflow.universalIdentifier
+ ] as UniversalFlatWorkflow
+ ).flatUniversalWorkflowVersion?.id,
+ ).toBe(
+ (
+ before.flatWorkflowMaps.byUniversalIdentifier[
+ workflow.universalIdentifier
+ ] as UniversalFlatWorkflow
+ ).flatUniversalWorkflowVersion?.id,
+ );
+ });
+
+ it('rejects deleting a workflow on a full sync', () => {
+ expect(() =>
+ compute({ workflows: [], fromAllFlatEntityMaps: compute() }),
+ ).toThrow('Removing application workflows is not supported');
+ });
+
+ it('allows omitted workflows on additive syncs', () => {
+ expect(() =>
+ compute({
+ workflows: [],
+ fromAllFlatEntityMaps: compute(),
+ inferDeletionFromMissingEntities: false,
+ }),
+ ).not.toThrow();
+ });
+
+ it('rejects unknown record fields and update selections in one error', () => {
+ const objectUniversalIdentifier = '88888888-8888-4888-8888-888888888888';
+ const existing = createEmptyAllFlatEntityMaps();
+ existing.flatObjectMetadataMaps.byUniversalIdentifier[
+ objectUniversalIdentifier
+ ] = {
+ universalIdentifier: objectUniversalIdentifier,
+ applicationId: '99999999-9999-4999-8999-999999999999',
+ nameSingular: 'company',
+ } as FlatObjectMetadata;
+ const workflows = structuredClone(MANIFEST.workflows ?? []);
+ const workflow = workflows[0];
+ if (!isDefined(workflow)) {
+ throw new Error('Expected workflow');
+ }
+ workflow.version.steps = [
+ {
+ universalIdentifier: '66666666-6666-4666-8666-666666666666',
+ name: 'Update',
+ type: 'UPDATE_RECORD',
+ nextStepIds: [],
+ input: {
+ objectUniversalIdentifier,
+ objectRecordId: 'record',
+ objectRecord: { missing: true },
+ fieldsToUpdate: ['missing'],
+ },
+ },
+ ];
+
+ expect(() =>
+ compute({ workflows, fromAllFlatEntityMaps: existing }),
+ ).toThrow(/unknown record field missing.*fieldsToUpdate/);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/compute-workflow-manifest-order-by.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/compute-workflow-manifest-order-by.util.spec.ts
new file mode 100644
index 00000000000..1517ee3c3c6
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/compute-workflow-manifest-order-by.util.spec.ts
@@ -0,0 +1,95 @@
+import { FieldMetadataType } from 'twenty-shared/types';
+
+import { computeWorkflowManifestOrderBy } from 'src/engine/core-modules/application/application-manifest/utils/compute-workflow-manifest-order-by.util';
+import { type WorkflowManifestFieldReference } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
+
+const field: WorkflowManifestFieldReference = {
+ id: 'field',
+ name: 'value',
+ objectUniversalIdentifier: 'company',
+ type: FieldMetadataType.TEXT,
+ settings: null,
+ relationTargetObjectMetadataUniversalIdentifier: null,
+};
+const references = {
+ logicFunctionIdByUniversalIdentifier: new Map<string, string>(),
+};
+
+describe('workflow manifest executable ordering', () => {
+ it.each([
+ [FieldMetadataType.TEXT, [{ value: 'DescNullsLast' }]],
+ [
+ FieldMetadataType.CURRENCY,
+ [{ value: { amountMicros: 'DescNullsLast' } }],
+ ],
+ [
+ FieldMetadataType.FULL_NAME,
+ [
+ { value: { firstName: 'DescNullsLast' } },
+ { value: { lastName: 'DescNullsLast' } },
+ ],
+ ],
+ ])('sorts %s fields by the runtime GraphQL shape', (type, expected) => {
+ expect(
+ computeWorkflowManifestOrderBy({
+ field: { ...field, type },
+ direction: 'DESC',
+ references,
+ }),
+ ).toEqual(expected);
+ });
+
+ it('honors enabled address subfields', () => {
+ expect(
+ computeWorkflowManifestOrderBy({
+ field: {
+ ...field,
+ type: FieldMetadataType.ADDRESS,
+ settings: { subFields: ['addressCountry', 'addressCity'] },
+ },
+ direction: 'ASC',
+ subFieldName: 'addressCountry',
+ references,
+ }),
+ ).toEqual([{ value: { addressCountry: 'AscNullsLast' } }]);
+ });
+
+ it('sorts relations by the target label rather than a relation scalar', () => {
+ expect(
+ computeWorkflowManifestOrderBy({
+ field: {
+ ...field,
+ type: FieldMetadataType.RELATION,
+ relationTargetObjectMetadataUniversalIdentifier: 'person',
+ },
+ direction: 'ASC',
+ references: {
+ ...references,
+ objectByUniversalIdentifier: new Map([
+ [
+ 'person',
+ {
+ nameSingular: 'person',
+ labelIdentifierFieldMetadataUniversalIdentifier: 'label',
+ },
+ ],
+ ]),
+ fieldByUniversalIdentifier: new Map([
+ [
+ 'label',
+ {
+ ...field,
+ name: 'name',
+ objectUniversalIdentifier: 'person',
+ type: FieldMetadataType.FULL_NAME,
+ },
+ ],
+ ]),
+ },
+ }),
+ ).toEqual([
+ { value: { name: { firstName: 'AscNullsLast' } } },
+ { value: { name: { lastName: 'AscNullsLast' } } },
+ ]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/preallocate-workflow-reference-ids.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/preallocate-workflow-reference-ids.util.spec.ts
new file mode 100644
index 00000000000..304aa60b62d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/preallocate-workflow-reference-ids.util.spec.ts
@@ -0,0 +1,52 @@
+import { preallocateWorkflowReferenceIds } from 'src/engine/core-modules/application/application-manifest/utils/preallocate-workflow-reference-ids.util';
+import { createEmptyAllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-all-flat-entity-maps.constant';
+import { type FlatAgent } from 'src/engine/metadata-modules/flat-agent/types/flat-agent.type';
+import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
+import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
+
+describe('preallocateWorkflowReferenceIds', () => {
+ it('reuses installed IDs, allocates new ones and leaves definitions untouched', () => {
+ const installed = createEmptyAllFlatEntityMaps();
+ installed.flatLogicFunctionMaps.byUniversalIdentifier.greet = {
+ universalIdentifier: 'greet',
+ id: 'installed-greet',
+ } as FlatLogicFunction;
+ installed.flatAgentMaps.byUniversalIdentifier.summarize = {
+ universalIdentifier: 'summarize',
+ id: 'installed-summarize',
+ } as FlatAgent;
+ installed.flatFieldMetadataMaps.byUniversalIdentifier.name = {
+ universalIdentifier: 'name',
+ id: 'installed-name',
+ } as FlatFieldMetadata;
+
+ const proposed = createEmptyAllFlatEntityMaps();
+ proposed.flatLogicFunctionMaps.byUniversalIdentifier.greet = {
+ universalIdentifier: 'greet',
+ } as FlatLogicFunction;
+ proposed.flatAgentMaps.byUniversalIdentifier.summarize = {
+ universalIdentifier: 'summarize',
+ } as FlatAgent;
+ proposed.flatFieldMetadataMaps.byUniversalIdentifier.name = {
+ universalIdentifier: 'name',
+ } as FlatFieldMetadata;
+ proposed.flatFieldMetadataMaps.byUniversalIdentifier.score = {
+ universalIdentifier: 'score',
+ } as FlatFieldMetadata;
+
+ const ids = preallocateWorkflowReferenceIds({
+ fromAllFlatEntityMaps: installed,
+ toAllUniversalFlatEntityMaps: proposed,
+ });
+
+ expect(ids).toEqual({
+ logicFunction: { greet: 'installed-greet' },
+ agent: { summarize: 'installed-summarize' },
+ fieldMetadata: { name: 'installed-name', score: expect.any(String) },
+ });
+ expect(ids.fieldMetadata?.score).not.toBe(ids.fieldMetadata?.name);
+ expect(proposed.flatFieldMetadataMaps.byUniversalIdentifier.score?.id).toBe(
+ undefined,
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/prepare-workflow-manifest-references.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/prepare-workflow-manifest-references.util.spec.ts
new file mode 100644
index 00000000000..e1ea0d5c69a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/prepare-workflow-manifest-references.util.spec.ts
@@ -0,0 +1,134 @@
+import { createEmptyAllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-all-flat-entity-maps.constant';
+import { type FlatAgent } from 'src/engine/metadata-modules/flat-agent/types/flat-agent.type';
+import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
+import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+import { prepareWorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/utils/prepare-workflow-manifest-references.util';
+
+const OWNER = 'owner';
+const object = {
+ universalIdentifier: 'object',
+ nameSingular: 'company',
+ applicationId: OWNER,
+} as FlatObjectMetadata;
+const field = {
+ universalIdentifier: 'field',
+ name: 'name',
+ objectMetadataUniversalIdentifier: 'object',
+ applicationId: OWNER,
+} as FlatFieldMetadata;
+const agent = { universalIdentifier: 'agent' } as FlatAgent;
+const codeFunction = {
+ universalIdentifier: 'code',
+ workflowActionTriggerSettings: null,
+} as FlatLogicFunction;
+const actionFunction = {
+ universalIdentifier: 'action',
+ workflowActionTriggerSettings: {},
+} as FlatLogicFunction;
+
+const proposedMaps = () => {
+ const maps = createEmptyAllFlatEntityMaps();
+ maps.flatObjectMetadataMaps.byUniversalIdentifier.object = { ...object };
+ maps.flatFieldMetadataMaps.byUniversalIdentifier.field = { ...field };
+ maps.flatAgentMaps.byUniversalIdentifier.agent = { ...agent };
+ maps.flatLogicFunctionMaps.byUniversalIdentifier.code = { ...codeFunction };
+ maps.flatLogicFunctionMaps.byUniversalIdentifier.action = {
+ ...actionFunction,
+ };
+ return maps;
+};
+
+describe('workflow manifest references', () => {
+ it('resolves function and agent output schemas from the same installation', () => {
+ const proposed = proposedMaps();
+ proposed.flatLogicFunctionMaps.byUniversalIdentifier.action!.workflowActionTriggerSettings =
+ {
+ outputSchema: [
+ { type: 'object', properties: { greeting: { type: 'string' } } },
+ ],
+ };
+ proposed.flatAgentMaps.byUniversalIdentifier.agent!.responseFormat = {
+ type: 'json',
+ schema: {
+ type: 'object',
+ properties: {
+ summary: { type: 'string', description: 'Summary' },
+ score: { type: 'number' },
+ },
+ },
+ };
+ const references = prepareWorkflowManifestReferences({
+ existingAllFlatEntityMaps: createEmptyAllFlatEntityMaps(),
+ toAllUniversalFlatEntityMaps: proposed,
+ ownerApplicationId: OWNER,
+ idByUniversalIdentifierByMetadataName: {},
+ });
+ expect(
+ references.logicFunctionOutputSchemaByUniversalIdentifier?.get('action'),
+ ).toMatchObject({ greeting: { isLeaf: true, type: 'string' } });
+ expect(
+ references.agentOutputSchemaByUniversalIdentifier?.get('agent'),
+ ).toMatchObject({
+ summary: { isLeaf: true, type: 'string', description: 'Summary' },
+ score: { type: 'number' },
+ });
+ });
+
+ it('uses preallocated IDs without assigning them to the definitions', () => {
+ const proposed = proposedMaps();
+ const references = prepareWorkflowManifestReferences({
+ existingAllFlatEntityMaps: createEmptyAllFlatEntityMaps(),
+ toAllUniversalFlatEntityMaps: proposed,
+ ownerApplicationId: OWNER,
+ idByUniversalIdentifierByMetadataName: {
+ logicFunction: { code: 'code-id', action: 'action-id' },
+ agent: { agent: 'agent-id' },
+ fieldMetadata: { field: 'field-id' },
+ },
+ });
+ expect(
+ references.objectByUniversalIdentifier?.get('object')?.nameSingular,
+ ).toBe('company');
+ expect(references.fieldByUniversalIdentifier?.get('field')?.id).toBe(
+ 'field-id',
+ );
+ expect(references.agentIdByUniversalIdentifier?.get('agent')).toBe(
+ 'agent-id',
+ );
+ expect(references.logicFunctionIdByUniversalIdentifier.has('code')).toBe(
+ false,
+ );
+ expect(references.logicFunctionIdByUniversalIdentifier.get('action')).toBe(
+ 'action-id',
+ );
+ expect(proposed.flatFieldMetadataMaps.byUniversalIdentifier.field?.id).toBe(
+ undefined,
+ );
+ expect(proposed.flatAgentMaps.byUniversalIdentifier.agent?.id).toBe(
+ undefined,
+ );
+ expect(
+ proposed.flatLogicFunctionMaps.byUniversalIdentifier.action?.id,
+ ).toBe(undefined);
+ });
+
+ it('allows installed dependency metadata but excludes removed application metadata', () => {
+ const installed = proposedMaps();
+ installed.flatObjectMetadataMaps.byUniversalIdentifier.standard = {
+ ...object,
+ universalIdentifier: 'standard',
+ applicationId: 'standard-application',
+ };
+ const references = prepareWorkflowManifestReferences({
+ existingAllFlatEntityMaps: installed,
+ toAllUniversalFlatEntityMaps: createEmptyAllFlatEntityMaps(),
+ ownerApplicationId: OWNER,
+ idByUniversalIdentifierByMetadataName: {},
+ });
+ expect(references.objectByUniversalIdentifier?.has('standard')).toBe(true);
+ expect(references.objectByUniversalIdentifier?.has('object')).toBe(false);
+ expect(references.fieldByUniversalIdentifier?.has('field')).toBe(false);
+ expect(references.agentIdByUniversalIdentifier?.size).toBe(0);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/validate-workflow-manifest-record-fields.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/validate-workflow-manifest-record-fields.util.spec.ts
new file mode 100644
index 00000000000..fa46e3f0097
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/validate-workflow-manifest-record-fields.util.spec.ts
@@ -0,0 +1,53 @@
+import { FieldMetadataType, RelationType } from 'twenty-shared/types';
+
+import { type WorkflowManifestFieldReference } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
+import { validateWorkflowManifestRecordFields } from 'src/engine/core-modules/application/application-manifest/utils/validate-workflow-manifest-record-fields.util';
+import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+
+const COMPANY_ID = '11111111-1111-4111-8111-111111111111';
+
+const ownerField = {
+ objectUniversalIdentifier: COMPANY_ID,
+ id: '22222222-2222-4222-8222-222222222222',
+ name: 'owner',
+ type: FieldMetadataType.RELATION,
+ settings: null,
+ relationTargetObjectMetadataUniversalIdentifier: null,
+ universalSettings: { relationType: RelationType.MANY_TO_ONE },
+} as WorkflowManifestFieldReference;
+
+const validateUpdate = (
+ objectRecord: Record<string, unknown>,
+ fieldsToUpdate: string[],
+) =>
+ validateWorkflowManifestRecordFields({
+ steps: [
+ {
+ id: '33333333-3333-4333-8333-333333333333',
+ name: 'Update',
+ type: 'UPDATE_RECORD',
+ valid: true,
+ settings: {
+ input: {
+ objectName: 'company',
+ objectRecordId: 'record',
+ objectRecord,
+ fieldsToUpdate,
+ },
+ },
+ } as WorkflowAction,
+ ],
+ objectByUniversalIdentifier: new Map([
+ [COMPANY_ID, { nameSingular: 'company' }],
+ ]),
+ fieldByUniversalIdentifier: new Map([[ownerField.id, ownerField]]),
+ });
+
+describe('validateWorkflowManifestRecordFields', () => {
+ it('requires the join column to update a many-to-one relation', () => {
+ expect(validateUpdate({ owner: { id: 'person' } }, ['owner'])).toEqual([
+ expect.stringContaining('using the join column for relations'),
+ ]);
+ expect(validateUpdate({ ownerId: 'person' }, ['ownerId'])).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/add-workflow-manifests-to-flat-entity-maps-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/add-workflow-manifests-to-flat-entity-maps-or-throw.util.ts
new file mode 100644
index 00000000000..9e1137fcdb6
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/add-workflow-manifests-to-flat-entity-maps-or-throw.util.ts
@@ -0,0 +1,128 @@
+import { msg } from '@lingui/core/macro';
+
+import {
+ getWorkflowVersionUniversalIdentifier,
+ type WorkflowManifest,
+} from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { fromWorkflowManifestToUniversalFlatWorkflowOrThrow } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util';
+import { prepareWorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/utils/prepare-workflow-manifest-references.util';
+import { validateWorkflowManifestRecordFields } from 'src/engine/core-modules/application/application-manifest/utils/validate-workflow-manifest-record-fields.util';
+import {
+ ApplicationException,
+ ApplicationExceptionCode,
+} from 'src/engine/core-modules/application/application.exception';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
+import { type IdByUniversalIdentifierByMetadataName } from 'src/engine/workspace-manager/workspace-migration/services/utils/enrich-create-workspace-migration-action-with-ids.util';
+import { addUniversalFlatEntityToUniversalFlatEntityMapsThroughMutationOrThrow } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/utils/add-universal-flat-entity-to-universal-flat-entity-maps-through-mutation-or-throw.util';
+
+export const addWorkflowManifestsToFlatEntityMapsOrThrow = ({
+ workflows,
+ ownerFlatApplication,
+ fromAllFlatEntityMaps,
+ toAllUniversalFlatEntityMaps,
+ existingAllFlatEntityMaps,
+ idByUniversalIdentifierByMetadataName,
+ isApplicationWorkflowsEnabled,
+ inferDeletionFromMissingEntities,
+ now,
+}: {
+ workflows: WorkflowManifest[];
+ ownerFlatApplication: Pick<FlatApplication, 'id' | 'universalIdentifier'>;
+ fromAllFlatEntityMaps: AllFlatEntityMaps;
+ toAllUniversalFlatEntityMaps: AllFlatEntityMaps;
+ existingAllFlatEntityMaps: AllFlatEntityMaps;
+ idByUniversalIdentifierByMetadataName: IdByUniversalIdentifierByMetadataName;
+ isApplicationWorkflowsEnabled: boolean | undefined;
+ inferDeletionFromMissingEntities: boolean;
+ now: string;
+}): void => {
+ if (workflows.length > 0 && !isApplicationWorkflowsEnabled) {
+ throw new ApplicationException(
+ 'Application workflows are not enabled for this workspace',
+ ApplicationExceptionCode.INVALID_INPUT,
+ {
+ userFriendlyMessage: msg`Application workflows are not enabled for this workspace.`,
+ },
+ );
+ }
+
+ const applicationUniversalIdentifier =
+ ownerFlatApplication.universalIdentifier;
+
+ const declaredWorkflowIds = new Set(
+ workflows.map((workflow) => workflow.universalIdentifier),
+ );
+ for (const existing of Object.values(
+ fromAllFlatEntityMaps.flatWorkflowMaps.byUniversalIdentifier,
+ )) {
+ if (
+ inferDeletionFromMissingEntities &&
+ isDefined(existing) &&
+ !isDefined(existing.workspaceWorkflowId) &&
+ !declaredWorkflowIds.has(existing.universalIdentifier)
+ ) {
+ throw new ApplicationException(
+ 'Removing application workflows is not supported by the defineWorkflow POC; existing runs may still reference them',
+ ApplicationExceptionCode.INVALID_INPUT,
+ {
+ userFriendlyMessage: msg`Removing application workflows is not supported yet.`,
+ },
+ );
+ }
+ }
+
+ if (workflows.length > 0) {
+ const references = prepareWorkflowManifestReferences({
+ toAllUniversalFlatEntityMaps,
+ existingAllFlatEntityMaps,
+ ownerApplicationId: ownerFlatApplication.id,
+ idByUniversalIdentifierByMetadataName,
+ });
+ const recordFieldErrors: string[] = [];
+ for (const workflowManifest of workflows) {
+ const existingWorkflow =
+ fromAllFlatEntityMaps.flatWorkflowMaps.byUniversalIdentifier[
+ workflowManifest.universalIdentifier
+ ];
+ const existingVersion =
+ fromAllFlatEntityMaps.flatWorkflowVersionMaps.byUniversalIdentifier[
+ getWorkflowVersionUniversalIdentifier({
+ applicationUniversalIdentifier,
+ workflowUniversalIdentifier: workflowManifest.universalIdentifier,
+ })
+ ];
+ const workflow = fromWorkflowManifestToUniversalFlatWorkflowOrThrow({
+ manifest: workflowManifest,
+ applicationUniversalIdentifier,
+ existingWorkflow,
+ existingVersion,
+ ...references,
+ now,
+ });
+ recordFieldErrors.push(
+ ...validateWorkflowManifestRecordFields({
+ steps: workflow.flatUniversalWorkflowVersion?.steps ?? [],
+ objectByUniversalIdentifier: references.objectByUniversalIdentifier,
+ fieldByUniversalIdentifier: references.fieldByUniversalIdentifier,
+ }),
+ );
+ addUniversalFlatEntityToUniversalFlatEntityMapsThroughMutationOrThrow({
+ universalFlatEntity: workflow,
+ universalFlatEntityMapsToMutate:
+ toAllUniversalFlatEntityMaps.flatWorkflowMaps,
+ });
+ }
+ if (recordFieldErrors.length > 0) {
+ throw new ApplicationException(
+ `Invalid application workflow definition: ${recordFieldErrors.join('; ')}`,
+ ApplicationExceptionCode.INVALID_INPUT,
+ {
+ userFriendlyMessage: msg`The application workflow definition is invalid.`,
+ },
+ );
+ }
+ }
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/can-manifest-express-flat-entity.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/can-manifest-express-flat-entity.util.ts
index 706d9b4bbd5..8c8f4aeea09 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/can-manifest-express-flat-entity.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/can-manifest-express-flat-entity.util.ts
@@ -3,6 +3,7 @@ import { isDefined } from 'twenty-shared/utils';
const METADATA_NAMES_WITHOUT_MANIFEST_REPRESENTATION: AllMetadataName[] = [
'webhook',
+ 'workflowVersion',
];
const WORKSPACE_BOUND_PROPERTIES = [
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-manifest-order-by.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-manifest-order-by.util.ts
new file mode 100644
index 00000000000..e2bfab7b216
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-manifest-order-by.util.ts
@@ -0,0 +1,48 @@
+import {
+ getOrderByForFieldMetadataType,
+ getOrderByForRelationField,
+} from 'twenty-shared/utils';
+import {
+ FieldMetadataType,
+ type RecordGqlOperationOrderBy,
+} from 'twenty-shared/types';
+import {
+ type WorkflowManifestFieldReference,
+ type WorkflowManifestReferences,
+} from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
+
+export const computeWorkflowManifestOrderBy = ({
+ field,
+ direction,
+ subFieldName,
+ references,
+}: {
+ field: WorkflowManifestFieldReference;
+ direction: 'ASC' | 'DESC';
+ subFieldName?: string | null;
+ references: WorkflowManifestReferences;
+}): RecordGqlOperationOrderBy => {
+ const orderByDirection =
+ direction === 'ASC' ? 'AscNullsLast' : 'DescNullsLast';
+ if (field.type === FieldMetadataType.RELATION) {
+ const target = references.objectByUniversalIdentifier?.get(
+ field.relationTargetObjectMetadataUniversalIdentifier ?? '',
+ );
+ const labelIdentifierField = references.fieldByUniversalIdentifier?.get(
+ target?.labelIdentifierFieldMetadataUniversalIdentifier ?? '',
+ );
+ return getOrderByForRelationField({
+ field,
+ labelIdentifierField:
+ labelIdentifierField?.type === FieldMetadataType.RELATION
+ ? undefined
+ : labelIdentifierField,
+ orderByDirection,
+ });
+ }
+ return getOrderByForFieldMetadataType({
+ field,
+ orderByDirection,
+ primaryCompositeSubField: subFieldName,
+ });
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-manifest-output-schema.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-manifest-output-schema.util.ts
new file mode 100644
index 00000000000..50e56149e50
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-manifest-output-schema.util.ts
@@ -0,0 +1,47 @@
+import { type WorkflowStepManifest } from 'twenty-shared/application';
+import { getOutputSchemaFromValue } from 'twenty-shared/logic-function';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
+import { computeAiAgentOutputSchema } from 'src/modules/workflow/workflow-builder/workflow-schema/utils/compute-ai-agent-output-schema.util';
+
+export const computeWorkflowManifestOutputSchema = ({
+ step,
+ references,
+}: {
+ step: WorkflowStepManifest;
+ references: WorkflowManifestReferences;
+}): Record<string, unknown> => {
+ if (
+ isDefined(step.outputSchema) &&
+ Object.keys(step.outputSchema).length > 0
+ ) {
+ return step.outputSchema;
+ }
+
+ if (step.type === 'LOGIC_FUNCTION') {
+ const declaredOutputSchema =
+ references.logicFunctionOutputSchemaByUniversalIdentifier?.get(
+ step.logicFunctionUniversalIdentifier,
+ );
+
+ if (
+ isDefined(declaredOutputSchema) &&
+ Object.keys(declaredOutputSchema).length > 0
+ ) {
+ return declaredOutputSchema;
+ }
+ }
+
+ if (step.type === 'AI_AGENT') {
+ return isDefined(step.input.agentUniversalIdentifier)
+ ? (references.agentOutputSchemaByUniversalIdentifier?.get(
+ step.input.agentUniversalIdentifier,
+ ) ?? computeAiAgentOutputSchema())
+ : computeAiAgentOutputSchema();
+ }
+
+ return isDefined(step.expectedOutputSchema)
+ ? getOutputSchemaFromValue(step.expectedOutputSchema)
+ : {};
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/preallocate-workflow-reference-ids.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/preallocate-workflow-reference-ids.util.ts
new file mode 100644
index 00000000000..afbf4caa945
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/preallocate-workflow-reference-ids.util.ts
@@ -0,0 +1,50 @@
+import { v4 } from 'uuid';
+
+import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
+import { type IdByUniversalIdentifierByMetadataName } from 'src/engine/workspace-manager/workspace-migration/services/utils/enrich-create-workspace-migration-action-with-ids.util';
+
+const preallocateIds = ({
+ toByUniversalIdentifier,
+ fromByUniversalIdentifier,
+}: {
+ toByUniversalIdentifier: Partial<Record<string, unknown>>;
+ fromByUniversalIdentifier: Partial<Record<string, { id: string }>>;
+}): Record<string, string> => {
+ return Object.fromEntries(
+ Object.keys(toByUniversalIdentifier).map((universalIdentifier) => [
+ universalIdentifier,
+ fromByUniversalIdentifier[universalIdentifier]?.id ?? v4(),
+ ]),
+ );
+};
+
+export const preallocateWorkflowReferenceIds = ({
+ fromAllFlatEntityMaps,
+ toAllUniversalFlatEntityMaps,
+}: {
+ fromAllFlatEntityMaps: AllFlatEntityMaps;
+ toAllUniversalFlatEntityMaps: AllFlatEntityMaps;
+}): IdByUniversalIdentifierByMetadataName => {
+ return {
+ logicFunction: preallocateIds({
+ toByUniversalIdentifier:
+ toAllUniversalFlatEntityMaps.flatLogicFunctionMaps
+ .byUniversalIdentifier,
+ fromByUniversalIdentifier:
+ fromAllFlatEntityMaps.flatLogicFunctionMaps.byUniversalIdentifier,
+ }),
+ agent: preallocateIds({
+ toByUniversalIdentifier:
+ toAllUniversalFlatEntityMaps.flatAgentMaps.byUniversalIdentifier,
+ fromByUniversalIdentifier:
+ fromAllFlatEntityMaps.flatAgentMaps.byUniversalIdentifier,
+ }),
+ fieldMetadata: preallocateIds({
+ toByUniversalIdentifier:
+ toAllUniversalFlatEntityMaps.flatFieldMetadataMaps
+ .byUniversalIdentifier,
+ fromByUniversalIdentifier:
+ fromAllFlatEntityMaps.flatFieldMetadataMaps.byUniversalIdentifier,
+ }),
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/prepare-workflow-manifest-references.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/prepare-workflow-manifest-references.util.ts
new file mode 100644
index 00000000000..5781206a92a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/prepare-workflow-manifest-references.util.ts
@@ -0,0 +1,139 @@
+import { inputSchemaToOutputSchema } from 'twenty-shared/logic-function';
+import { type BaseOutputSchemaV2 } from 'twenty-shared/workflow';
+import { computeAiAgentOutputSchema } from 'src/modules/workflow/workflow-builder/workflow-schema/utils/compute-ai-agent-output-schema.util';
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ type WorkflowManifestReferences,
+ type WorkflowManifestObjectReference,
+ type WorkflowManifestFieldReference,
+} from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
+import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
+import { type IdByUniversalIdentifierByMetadataName } from 'src/engine/workspace-manager/workspace-migration/services/utils/enrich-create-workspace-migration-action-with-ids.util';
+
+export const prepareWorkflowManifestReferences = ({
+ toAllUniversalFlatEntityMaps,
+ existingAllFlatEntityMaps,
+ ownerApplicationId,
+ idByUniversalIdentifierByMetadataName,
+}: {
+ toAllUniversalFlatEntityMaps: AllFlatEntityMaps;
+ existingAllFlatEntityMaps: AllFlatEntityMaps;
+ ownerApplicationId: string;
+ idByUniversalIdentifierByMetadataName: IdByUniversalIdentifierByMetadataName;
+}): WorkflowManifestReferences => {
+ const logicFunctionOutputSchemaByUniversalIdentifier = new Map<
+ string,
+ BaseOutputSchemaV2
+ >();
+ const agentOutputSchemaByUniversalIdentifier = new Map<
+ string,
+ BaseOutputSchemaV2
+ >();
+ const logicFunctionIdByUniversalIdentifier = new Map<string, string>();
+ const agentIdByUniversalIdentifier = new Map<string, string>();
+ const objectByUniversalIdentifier = new Map<
+ string,
+ WorkflowManifestObjectReference
+ >();
+ const fieldByUniversalIdentifier = new Map<
+ string,
+ WorkflowManifestFieldReference
+ >();
+
+ for (const logicFunction of Object.values(
+ toAllUniversalFlatEntityMaps.flatLogicFunctionMaps.byUniversalIdentifier,
+ )) {
+ if (!isDefined(logicFunction)) {
+ continue;
+ }
+ const declaredOutputSchema =
+ logicFunction.workflowActionTriggerSettings?.outputSchema;
+ if (isDefined(declaredOutputSchema)) {
+ logicFunctionOutputSchemaByUniversalIdentifier.set(
+ logicFunction.universalIdentifier,
+ inputSchemaToOutputSchema(declaredOutputSchema),
+ );
+ }
+ const logicFunctionId =
+ idByUniversalIdentifierByMetadataName.logicFunction?.[
+ logicFunction.universalIdentifier
+ ];
+ if (
+ isDefined(logicFunction.workflowActionTriggerSettings) &&
+ isDefined(logicFunctionId)
+ ) {
+ logicFunctionIdByUniversalIdentifier.set(
+ logicFunction.universalIdentifier,
+ logicFunctionId,
+ );
+ }
+ }
+ for (const agent of Object.values(
+ toAllUniversalFlatEntityMaps.flatAgentMaps.byUniversalIdentifier,
+ )) {
+ if (!isDefined(agent)) {
+ continue;
+ }
+ const agentId =
+ idByUniversalIdentifierByMetadataName.agent?.[agent.universalIdentifier];
+ if (isDefined(agentId)) {
+ agentIdByUniversalIdentifier.set(agent.universalIdentifier, agentId);
+ }
+ agentOutputSchemaByUniversalIdentifier.set(
+ agent.universalIdentifier,
+ computeAiAgentOutputSchema(agent.responseFormat),
+ );
+ }
+ for (const object of Object.values(
+ existingAllFlatEntityMaps.flatObjectMetadataMaps.byUniversalIdentifier,
+ )) {
+ if (isDefined(object) && object.applicationId !== ownerApplicationId) {
+ objectByUniversalIdentifier.set(object.universalIdentifier, object);
+ }
+ }
+ for (const field of Object.values(
+ existingAllFlatEntityMaps.flatFieldMetadataMaps.byUniversalIdentifier,
+ )) {
+ if (isDefined(field) && field.applicationId !== ownerApplicationId) {
+ fieldByUniversalIdentifier.set(field.universalIdentifier, {
+ ...field,
+ objectUniversalIdentifier: field.objectMetadataUniversalIdentifier,
+ });
+ }
+ }
+ for (const object of Object.values(
+ toAllUniversalFlatEntityMaps.flatObjectMetadataMaps.byUniversalIdentifier,
+ )) {
+ if (isDefined(object)) {
+ objectByUniversalIdentifier.set(object.universalIdentifier, object);
+ }
+ }
+ for (const field of Object.values(
+ toAllUniversalFlatEntityMaps.flatFieldMetadataMaps.byUniversalIdentifier,
+ )) {
+ if (!isDefined(field)) {
+ continue;
+ }
+ const fieldId =
+ idByUniversalIdentifierByMetadataName.fieldMetadata?.[
+ field.universalIdentifier
+ ];
+ if (!isDefined(fieldId)) {
+ continue;
+ }
+ fieldByUniversalIdentifier.set(field.universalIdentifier, {
+ ...field,
+ id: fieldId,
+ objectUniversalIdentifier: field.objectMetadataUniversalIdentifier,
+ });
+ }
+ return {
+ logicFunctionOutputSchemaByUniversalIdentifier,
+ agentOutputSchemaByUniversalIdentifier,
+ logicFunctionIdByUniversalIdentifier,
+ agentIdByUniversalIdentifier,
+ objectByUniversalIdentifier,
+ fieldByUniversalIdentifier,
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/validate-workflow-manifest-record-fields.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/validate-workflow-manifest-record-fields.util.ts
new file mode 100644
index 00000000000..5cb0b5f0d0e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/validate-workflow-manifest-record-fields.util.ts
@@ -0,0 +1,135 @@
+import { FieldMetadataType, RelationType } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import {
+ type WorkflowManifestFieldReference,
+ type WorkflowManifestObjectReference,
+ type WorkflowManifestReferences,
+} from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
+import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+import { computeMorphOrRelationFieldJoinColumnName } from 'src/engine/metadata-modules/field-metadata/utils/compute-morph-or-relation-field-join-column-name.util';
+import { getMorphNameFromMorphFieldMetadataName } from 'src/engine/metadata-modules/flat-object-metadata/utils/get-morph-name-from-morph-field-metadata-name.util';
+
+type ObjectFieldNames = {
+ fieldNames: Set<string>;
+ relationNames: Set<string>;
+};
+
+export const validateWorkflowManifestRecordFields = ({
+ steps,
+ objectByUniversalIdentifier = new Map<
+ string,
+ WorkflowManifestObjectReference
+ >(),
+ fieldByUniversalIdentifier = new Map<
+ string,
+ WorkflowManifestFieldReference
+ >(),
+}: {
+ steps: WorkflowAction[];
+} & Pick<
+ WorkflowManifestReferences,
+ 'objectByUniversalIdentifier' | 'fieldByUniversalIdentifier'
+>): string[] => {
+ const errors: string[] = [];
+ const objectFieldsByObjectName = new Map<string, ObjectFieldNames>();
+ const objectFieldsByObjectIdentifier = new Map<string, ObjectFieldNames>();
+ for (const [universalIdentifier, object] of objectByUniversalIdentifier) {
+ const objectFields = {
+ fieldNames: new Set<string>(),
+ relationNames: new Set<string>(),
+ };
+ objectFieldsByObjectName.set(object.nameSingular, objectFields);
+ objectFieldsByObjectIdentifier.set(universalIdentifier, objectFields);
+ }
+ for (const field of fieldByUniversalIdentifier.values()) {
+ const objectFields = objectFieldsByObjectIdentifier.get(
+ field.objectUniversalIdentifier,
+ );
+ if (!isDefined(objectFields)) {
+ continue;
+ }
+ const { fieldNames, relationNames } = objectFields;
+ fieldNames.add(field.name);
+ if (
+ (field.type === FieldMetadataType.RELATION ||
+ field.type === FieldMetadataType.MORPH_RELATION) &&
+ isDefined(field.universalSettings) &&
+ 'relationType' in field.universalSettings &&
+ field.universalSettings.relationType === RelationType.MANY_TO_ONE
+ ) {
+ if (field.type === FieldMetadataType.RELATION) {
+ relationNames.add(field.name);
+ }
+ fieldNames.add(
+ computeMorphOrRelationFieldJoinColumnName({ name: field.name }),
+ );
+ const target = isDefined(
+ field.relationTargetObjectMetadataUniversalIdentifier,
+ )
+ ? objectByUniversalIdentifier.get(
+ field.relationTargetObjectMetadataUniversalIdentifier,
+ )
+ : undefined;
+ if (
+ field.type === FieldMetadataType.MORPH_RELATION &&
+ isDefined(target)
+ ) {
+ fieldNames.add(
+ getMorphNameFromMorphFieldMetadataName({
+ morphRelationFlatFieldMetadata: {
+ name: field.name,
+ universalSettings: { relationType: RelationType.MANY_TO_ONE },
+ },
+ nameSingular: target.nameSingular,
+ namePlural: target.namePlural ?? target.nameSingular,
+ }),
+ );
+ }
+ }
+ }
+
+ for (const step of steps) {
+ if (
+ step.type !== 'CREATE_RECORD' &&
+ step.type !== 'UPDATE_RECORD' &&
+ step.type !== 'UPSERT_RECORD'
+ ) {
+ continue;
+ }
+ const objectFields = objectFieldsByObjectName.get(
+ step.settings.input.objectName,
+ );
+ if (!isDefined(objectFields)) {
+ errors.push(
+ `Workflow step ${step.name}: unknown object ${step.settings.input.objectName}`,
+ );
+ continue;
+ }
+ const { fieldNames, relationNames } = objectFields;
+ for (const name of Object.keys(step.settings.input.objectRecord)) {
+ if (!fieldNames.has(name)) {
+ errors.push(`Workflow step ${step.name}: unknown record field ${name}`);
+ }
+ }
+
+ if (
+ step.type === 'UPDATE_RECORD' &&
+ (!isDefined(step.settings.input.fieldsToUpdate) ||
+ step.settings.input.fieldsToUpdate.length === 0 ||
+ step.settings.input.fieldsToUpdate.some(
+ (name) =>
+ !fieldNames.has(name) ||
+ relationNames.has(name) ||
+ !Object.prototype.hasOwnProperty.call(
+ step.settings.input.objectRecord,
+ name,
+ ),
+ ))
+ ) {
+ errors.push(
+ `Workflow step ${step.name}: fieldsToUpdate must select existing fields with values in objectRecord, using the join column for relations (ownerId, not owner)`,
+ );
+ }
+ }
+ return errors;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/core-workflow-access.module.ts b/packages/twenty-server/src/engine/core-modules/workflow/core-workflow-access.module.ts
index 9f3be74365e..82a32a67ae8 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/core-workflow-access.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/core-workflow-access.module.ts
@@ -1,3 +1,4 @@
+import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@@ -8,7 +9,10 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
// Own module: the command menu and the workflow API both need it and already depend on each other.
@Module({
- imports: [TypeOrmModule.forFeature([WorkflowEntity, WorkflowVersionEntity])],
+ imports: [
+ ApplicationModule,
+ TypeOrmModule.forFeature([WorkflowEntity, WorkflowVersionEntity]),
+ ],
providers: [
CoreWorkflowAccessService,
provideWorkspaceScopedRepository(WorkflowEntity),
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow-version.entity.ts b/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow-version.entity.ts
index 7030fa0e2fd..38f80fcb81a 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow-version.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow-version.entity.ts
@@ -1,3 +1,4 @@
+import { ADD_APPLICATION_WORKFLOW_SIDE_EFFECTS_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-45/add-application-workflow-side-effects-upgrade-command-name.constant';
import {
Column,
CreateDateColumn,
@@ -48,6 +49,13 @@ export class WorkflowVersionEntity extends SyncableEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
+ @WasIntroducedInUpgrade({
+ upgradeCommandName:
+ ADD_APPLICATION_WORKFLOW_SIDE_EFFECTS_UPGRADE_COMMAND_NAME,
+ })
+ @Column({ type: 'boolean', default: false })
+ isSystemSideEffect: boolean;
+
@Column({ type: 'jsonb', nullable: true })
triggers: WorkflowTrigger[] | null;
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow.entity.ts b/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow.entity.ts
index 100d72222bd..2095e72e071 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow.entity.ts
@@ -1,3 +1,4 @@
+import { ADD_APPLICATION_WORKFLOW_SIDE_EFFECTS_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-45/add-application-workflow-side-effects-upgrade-command-name.constant';
import {
Column,
CreateDateColumn,
@@ -38,6 +39,13 @@ export class WorkflowEntity extends SyncableEntity {
@Column({ type: 'text', nullable: true })
name: string | null;
+ @WasIntroducedInUpgrade({
+ upgradeCommandName:
+ ADD_APPLICATION_WORKFLOW_SIDE_EFFECTS_UPGRADE_COMMAND_NAME,
+ })
+ @Column({ type: 'text', nullable: true })
+ versionDefinitionHash: string | null;
+
@Column({ type: 'uuid', nullable: true })
lastPublishedVersionId: string | null;
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/exceptions/core-workflow-metadata.exception.ts b/packages/twenty-server/src/engine/core-modules/workflow/exceptions/core-workflow-metadata.exception.ts
index 34277194e17..c43523f2cf5 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/exceptions/core-workflow-metadata.exception.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/exceptions/core-workflow-metadata.exception.ts
@@ -4,6 +4,7 @@ import { assertUnreachable } from 'twenty-shared/utils';
import { CustomException } from 'src/utils/custom-exception';
export enum CoreWorkflowMetadataExceptionCode {
+ INVALID_WORKFLOW_VERSION_DEFINITION = 'INVALID_WORKFLOW_VERSION_DEFINITION',
WORKFLOW_NOT_FOUND = 'WORKFLOW_NOT_FOUND',
WORKFLOW_ALREADY_EXISTS = 'WORKFLOW_ALREADY_EXISTS',
WORKFLOW_VERSION_NOT_FOUND = 'WORKFLOW_VERSION_NOT_FOUND',
@@ -15,6 +16,8 @@ const getCoreWorkflowMetadataExceptionUserFriendlyMessage = (
code: CoreWorkflowMetadataExceptionCode,
) => {
switch (code) {
+ case CoreWorkflowMetadataExceptionCode.INVALID_WORKFLOW_VERSION_DEFINITION:
+ return msg`The application workflow definition is invalid.`;
case CoreWorkflowMetadataExceptionCode.WORKFLOW_NOT_FOUND:
return msg`Workflow not found.`;
case CoreWorkflowMetadataExceptionCode.WORKFLOW_ALREADY_EXISTS:
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts
index c433ee47278..173793ae323 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts
@@ -1,3 +1,4 @@
+import { ApplicationService } from 'src/engine/core-modules/application/application.service';
import { Injectable } from '@nestjs/common';
import { msg } from '@lingui/core/macro';
@@ -20,12 +21,48 @@ import {
@Injectable()
export class CoreWorkflowAccessService {
constructor(
+ private readonly applicationService: ApplicationService,
@InjectWorkspaceScopedRepository(WorkflowEntity)
private readonly coreWorkflowRepository: WorkspaceScopedRepository<WorkflowEntity>,
@InjectWorkspaceScopedRepository(WorkflowVersionEntity)
private readonly coreWorkflowVersionRepository: WorkspaceScopedRepository<WorkflowVersionEntity>,
) {}
+ async assertCoreWorkflowsAreEditableOrThrow(args: {
+ workspaceId: string;
+ userWorkspaceId: string | undefined;
+ coreWorkflowIds: string[];
+ }): Promise<void> {
+ if (args.coreWorkflowIds.length === 0) {
+ return;
+ }
+
+ await this.assertCoreWorkflowsAreAccessibleOrThrow(args);
+ const { workspaceCustomFlatApplication, twentyStandardFlatApplication } =
+ await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
+ { workspaceId: args.workspaceId },
+ );
+ const workflows = await this.coreWorkflowRepository.find(args.workspaceId, {
+ where: { id: In(args.coreWorkflowIds) },
+ select: { id: true, applicationId: true },
+ });
+ if (
+ workflows.some(
+ (workflow) =>
+ workflow.applicationId !== workspaceCustomFlatApplication.id &&
+ workflow.applicationId !== twentyStandardFlatApplication.id,
+ )
+ ) {
+ throw new WorkflowQueryValidationException(
+ 'Application workflows can only be changed by synchronizing their application',
+ WorkflowQueryValidationExceptionCode.FORBIDDEN,
+ {
+ userFriendlyMessage: msg`This workflow is managed by an application and is read-only`,
+ },
+ );
+ }
+ }
+
async assertCoreWorkflowsAreAccessibleOrThrow({
workspaceId,
userWorkspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-id-resolution.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-id-resolution.service.ts
index 956c85f4a9f..bdfb5c18f93 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-id-resolution.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-id-resolution.service.ts
@@ -84,6 +84,16 @@ export class CoreWorkflowIdResolutionService {
},
);
+ if (isDefined(coreWorkflowVersion.coreWorkflowId)) {
+ await this.coreWorkflowAccessService.assertCoreWorkflowsAreEditableOrThrow(
+ {
+ workspaceId,
+ userWorkspaceId,
+ coreWorkflowIds: [coreWorkflowVersion.coreWorkflowId],
+ },
+ );
+ }
+
const workspaceWorkflowVersionId =
coreWorkflowVersion.workspaceWorkflowVersionId;
@@ -130,9 +140,11 @@ export class CoreWorkflowIdResolutionService {
);
}
- await this.coreWorkflowAccessService.assertCoreWorkflowsAreAccessibleOrThrow(
- { workspaceId, userWorkspaceId, coreWorkflowIds: [coreWorkflow.id] },
- );
+ await this.coreWorkflowAccessService.assertCoreWorkflowsAreEditableOrThrow({
+ workspaceId,
+ userWorkspaceId,
+ coreWorkflowIds: [coreWorkflow.id],
+ });
const workspaceWorkflowId = coreWorkflow.workspaceWorkflowId;
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts
index 0860a6779ee..f5d65e35c50 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts
@@ -350,13 +350,11 @@ export class CoreWorkflowMutationWorkspaceService {
coreWorkflowId: string;
name: string;
}): Promise<void> {
- await this.coreWorkflowAccessService.assertCoreWorkflowsAreAccessibleOrThrow(
- {
- workspaceId,
- userWorkspaceId,
- coreWorkflowIds: [coreWorkflowId],
- },
- );
+ await this.coreWorkflowAccessService.assertCoreWorkflowsAreEditableOrThrow({
+ workspaceId,
+ userWorkspaceId,
+ coreWorkflowIds: [coreWorkflowId],
+ });
const { workspaceWorkflowId } =
await this.coreWorkflowIdResolutionService.resolveWorkspaceWorkflowIdOrThrow(
@@ -483,6 +481,7 @@ export class CoreWorkflowMutationWorkspaceService {
createdByUserWorkspaceId: userWorkspaceId ?? null,
lastPublishedVersionId: null,
lastPublishedCoreWorkflowVersionId: null,
+ versionDefinitionHash: null,
createdAt,
updatedAt: createdAt,
};
@@ -580,13 +579,11 @@ export class CoreWorkflowMutationWorkspaceService {
userWorkspaceId: string | undefined;
coreWorkflowIds: string[];
}): Promise<DeletedCoreWorkflowDTO[]> {
- await this.coreWorkflowAccessService.assertCoreWorkflowsAreAccessibleOrThrow(
- {
- workspaceId,
- userWorkspaceId,
- coreWorkflowIds,
- },
- );
+ await this.coreWorkflowAccessService.assertCoreWorkflowsAreEditableOrThrow({
+ workspaceId,
+ userWorkspaceId,
+ coreWorkflowIds,
+ });
const coreWorkflowsToDelete = await this.coreWorkflowRepository.find(
workspaceId,
@@ -734,13 +731,11 @@ export class CoreWorkflowMutationWorkspaceService {
);
}
- await this.coreWorkflowAccessService.assertCoreWorkflowsAreAccessibleOrThrow(
- {
- workspaceId,
- userWorkspaceId,
- coreWorkflowIds: [coreVersion.coreWorkflowId],
- },
- );
+ await this.coreWorkflowAccessService.assertCoreWorkflowsAreEditableOrThrow({
+ workspaceId,
+ userWorkspaceId,
+ coreWorkflowIds: [coreVersion.coreWorkflowId],
+ });
const siblingCount = await this.coreWorkflowVersionRepository.count(
workspaceId,
@@ -899,13 +894,11 @@ export class CoreWorkflowMutationWorkspaceService {
workspaceId: string;
userWorkspaceId: string;
}): Promise<CoreWorkflowDTO | null> {
- await this.coreWorkflowAccessService.assertCoreWorkflowsAreAccessibleOrThrow(
- {
- workspaceId,
- userWorkspaceId,
- coreWorkflowIds: [coreWorkflowId],
- },
- );
+ await this.coreWorkflowAccessService.assertCoreWorkflowsAreEditableOrThrow({
+ workspaceId,
+ userWorkspaceId,
+ coreWorkflowIds: [coreWorkflowId],
+ });
// ownership is checked in the UPDATE's WHERE, not a prior read, so two concurrent claims of an ownerless workflow cannot both win;
// a workspace-visible workflow is already editable by every member, so claiming one grants no new access
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.ts
index d4f717cad56..61283f37fbc 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.ts
@@ -139,6 +139,16 @@ export class CoreWorkflowVersionWriteService {
);
}
+ if (isDefined(coreWorkflowVersion.coreWorkflowId)) {
+ await this.coreWorkflowAccessService.assertCoreWorkflowsAreEditableOrThrow(
+ {
+ workspaceId,
+ userWorkspaceId,
+ coreWorkflowIds: [coreWorkflowVersion.coreWorkflowId],
+ },
+ );
+ }
+
if (coreWorkflowVersion.status !== CoreWorkflowVersionStatus.DRAFT) {
throw new WorkflowQueryValidationException(
`Core workflow version '${coreWorkflowVersionId}' is not a draft`,
@@ -376,6 +386,7 @@ export class CoreWorkflowVersionWriteService {
triggers: isDefined(trigger) ? [trigger] : null,
steps: steps ?? null,
status: CoreWorkflowVersionStatus.DRAFT,
+ isSystemSideEffect: false,
workspaceWorkflowVersionId,
applicationUniversalIdentifier:
workspaceCustomFlatApplication.universalIdentifier,
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-core-sync.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-core-sync.service.ts
index 7529a75dae7..2829713c140 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-core-sync.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-core-sync.service.ts
@@ -209,6 +209,8 @@ export class WorkflowCoreSyncService {
const flatWorkflow: UniversalFlatWorkflow = {
universalIdentifier: coreRow.universalIdentifier,
name: coreRow.name,
+ versionDefinitionHash:
+ existingFlatWorkflow?.versionDefinitionHash ?? null,
workspaceWorkflowId: coreRow.workspaceWorkflowId,
lastPublishedVersionId: coreRow.lastPublishedVersionId,
lastPublishedCoreWorkflowVersionId:
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.ts
index d02d0a899cb..ccc113542f3 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.ts
@@ -211,6 +211,7 @@ export class WorkflowVersionCoreSyncService {
id: string;
} = {
...coreRow,
+ isSystemSideEffect: false,
coreWorkflowId:
coreRow.coreWorkflowId ??
existingFlatWorkflowVersion?.coreWorkflowId ??
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/all-universal-flat-entity-properties-to-compare-and-stringify.constant.spec.ts.snap b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/all-universal-flat-entity-properties-to-compare-and-stringify.constant.spec.ts.snap
index b5ab5d75be6..84ab9d50f0f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/all-universal-flat-entity-properties-to-compare-and-stringify.constant.spec.ts.snap
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/all-universal-flat-entity-properties-to-compare-and-stringify.constant.spec.ts.snap
@@ -505,6 +505,7 @@ exports[`ALL_UNIVERSAL_FLAT_ENTITY_PROPERTIES_TO_COMPARE_AND_STRINGIFY should ma
},
"workflow": {
"propertiesToCompare": [
+ "versionDefinitionHash",
"name",
"visibility",
"lastPublishedVersionId",
@@ -514,6 +515,7 @@ exports[`ALL_UNIVERSAL_FLAT_ENTITY_PROPERTIES_TO_COMPARE_AND_STRINGIFY should ma
},
"workflowVersion": {
"propertiesToCompare": [
+ "isSystemSideEffect",
"status",
"triggers",
"steps",
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts
index 0c3794a28c7..db817bcd675 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts
@@ -2114,6 +2114,11 @@ export const ALL_ENTITY_PROPERTIES_CONFIGURATION_BY_METADATA_NAME = {
},
},
workflow: {
+ versionDefinitionHash: {
+ toCompare: true,
+ toStringify: false,
+ universalProperty: undefined,
+ },
name: { toCompare: true, toStringify: false, universalProperty: undefined },
visibility: {
toCompare: true,
@@ -2152,6 +2157,11 @@ export const ALL_ENTITY_PROPERTIES_CONFIGURATION_BY_METADATA_NAME = {
},
},
workflowVersion: {
+ isSystemSideEffect: {
+ toCompare: true,
+ toStringify: false,
+ universalProperty: undefined,
+ },
status: {
toCompare: true,
toStringify: false,
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-side-effect-companion-metadata-names.constant.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-side-effect-companion-metadata-names.constant.ts
index 61914198d88..aa3dde0a3d4 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-side-effect-companion-metadata-names.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-side-effect-companion-metadata-names.constant.ts
@@ -1,6 +1,7 @@
import { type AllMetadataName } from 'twenty-shared/metadata';
export const ALL_METADATA_SIDE_EFFECT_COMPANION_METADATA_NAMES = {
+ workflow: ['workflowVersion'],
fieldMetadata: [
'index',
'searchFieldMetadata',
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/metadata-side-effect-handlers.module.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/metadata-side-effect-handlers.module.ts
index 15e9ebe0207..1f84b3d9a3a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/metadata-side-effect-handlers.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/metadata-side-effect-handlers.module.ts
@@ -1,3 +1,6 @@
+import { WorkflowVersionOnUpdateSideEffectHandlerService } from 'src/engine/metadata-modules/metadata-side-effect/handlers/workflow/services/workflow-version-on-update-side-effect-handler.service';
+import { WorkflowVersionOnCreateSideEffectHandlerService } from 'src/engine/metadata-modules/metadata-side-effect/handlers/workflow/services/workflow-version-on-create-side-effect-handler.service';
+import { WorkflowVersionOnDeleteSideEffectHandlerService } from 'src/engine/metadata-modules/metadata-side-effect/handlers/workflow/services/workflow-version-on-delete-side-effect-handler.service';
import { Module } from '@nestjs/common';
import { FieldSearchFieldMetadataOnCreateSideEffectHandlerService } from 'src/engine/metadata-modules/metadata-side-effect/handlers/field-metadata/services/field-search-field-metadata-on-create-side-effect-handler.service';
@@ -31,6 +34,9 @@ import { ObjectValidationRulesOnDeleteSideEffectHandlerService } from 'src/engin
@Module({
providers: [
+ WorkflowVersionOnUpdateSideEffectHandlerService,
+ WorkflowVersionOnCreateSideEffectHandlerService,
+ WorkflowVersionOnDeleteSideEffectHandlerService,
FieldUniqueBackingIndexOnCreateSideEffectHandlerService,
FieldUniqueBackingIndexOnUpdateSideEffectHandlerService,
FieldUniqueBackingIndexOnDeleteSideEffectHandlerService,
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/services/workflow-version-on-create-side-effect-handler.service.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/services/workflow-version-on-create-side-effect-handler.service.ts
new file mode 100644
index 00000000000..faa70e929be
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/services/workflow-version-on-create-side-effect-handler.service.ts
@@ -0,0 +1,25 @@
+import { Injectable } from '@nestjs/common';
+
+import { buildWorkflowVersionSideEffects } from 'src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/build-workflow-version-side-effects.util';
+import {
+ type BuildSideEffectsArgs,
+ MetadataSideEffectHandler,
+} from 'src/engine/metadata-modules/metadata-side-effect/interfaces/base-metadata-side-effect-handler.service';
+import { type MetadataSideEffectResult } from 'src/engine/metadata-modules/metadata-side-effect/types/metadata-side-effect-result.type';
+
+@Injectable()
+export class WorkflowVersionOnCreateSideEffectHandlerService extends MetadataSideEffectHandler(
+ {
+ operation: 'create',
+ metadataName: 'workflow',
+ name: 'workflowVersionOnCreate',
+ description:
+ 'Synchronize the managed version carried by an application workflow definition.',
+ },
+) {
+ buildSideEffects(
+ args: BuildSideEffectsArgs<'workflow'>,
+ ): MetadataSideEffectResult {
+ return buildWorkflowVersionSideEffects(args);
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/services/workflow-version-on-delete-side-effect-handler.service.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/services/workflow-version-on-delete-side-effect-handler.service.ts
new file mode 100644
index 00000000000..a2abbd226ae
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/services/workflow-version-on-delete-side-effect-handler.service.ts
@@ -0,0 +1,25 @@
+import { Injectable } from '@nestjs/common';
+
+import { buildWorkflowVersionDeleteSideEffects } from 'src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/build-workflow-version-delete-side-effects.util';
+import {
+ type BuildSideEffectsArgs,
+ MetadataSideEffectHandler,
+} from 'src/engine/metadata-modules/metadata-side-effect/interfaces/base-metadata-side-effect-handler.service';
+import { type MetadataSideEffectResult } from 'src/engine/metadata-modules/metadata-side-effect/types/metadata-side-effect-result.type';
+
+@Injectable()
+export class WorkflowVersionOnDeleteSideEffectHandlerService extends MetadataSideEffectHandler(
+ {
+ operation: 'delete',
+ metadataName: 'workflow',
+ name: 'workflowVersionOnDelete',
+ description:
+ 'Delete the managed version of an application workflow when the workflow is deleted.',
+ },
+) {
+ buildSideEffects(
+ args: BuildSideEffectsArgs<'workflow'>,
+ ): MetadataSideEffectResult {
+ return buildWorkflowVersionDeleteSideEffects(args);
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/services/workflow-version-on-update-side-effect-handler.service.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/services/workflow-version-on-update-side-effect-handler.service.ts
new file mode 100644
index 00000000000..ddfa36282ca
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/services/workflow-version-on-update-side-effect-handler.service.ts
@@ -0,0 +1,25 @@
+import { Injectable } from '@nestjs/common';
+
+import { buildWorkflowVersionSideEffects } from 'src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/build-workflow-version-side-effects.util';
+import {
+ type BuildSideEffectsArgs,
+ MetadataSideEffectHandler,
+} from 'src/engine/metadata-modules/metadata-side-effect/interfaces/base-metadata-side-effect-handler.service';
+import { type MetadataSideEffectResult } from 'src/engine/metadata-modules/metadata-side-effect/types/metadata-side-effect-result.type';
+
+@Injectable()
+export class WorkflowVersionOnUpdateSideEffectHandlerService extends MetadataSideEffectHandler(
+ {
+ operation: 'update',
+ metadataName: 'workflow',
+ name: 'workflowVersionOnUpdate',
+ description:
+ 'Synchronize the managed version carried by an application workflow definition.',
+ },
+) {
+ buildSideEffects(
+ args: BuildSideEffectsArgs<'workflow'>,
+ ): MetadataSideEffectResult {
+ return buildWorkflowVersionSideEffects(args);
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/__tests__/build-workflow-version-delete-side-effects.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/__tests__/build-workflow-version-delete-side-effects.util.spec.ts
new file mode 100644
index 00000000000..860f45a511e
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/__tests__/build-workflow-version-delete-side-effects.util.spec.ts
@@ -0,0 +1,64 @@
+import { getWorkflowVersionUniversalIdentifier } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { buildWorkflowVersionDeleteSideEffects } from 'src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/build-workflow-version-delete-side-effects.util';
+import { createEmptyAllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-all-flat-entity-maps.constant';
+import { type FlatWorkflowVersion } from 'src/engine/metadata-modules/flat-workflow-version/types/flat-workflow-version.type';
+import { type UniversalFlatWorkflow } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-workflow.type';
+
+const APPLICATION_ID = '11111111-1111-4111-8111-111111111111';
+const WORKFLOW_ID = '22222222-2222-4222-8222-222222222222';
+const VERSION_ID = getWorkflowVersionUniversalIdentifier({
+ applicationUniversalIdentifier: APPLICATION_ID,
+ workflowUniversalIdentifier: WORKFLOW_ID,
+});
+
+const deletedWorkflow = {
+ universalIdentifier: WORKFLOW_ID,
+ applicationUniversalIdentifier: APPLICATION_ID,
+} as UniversalFlatWorkflow;
+
+const buildDeleteSideEffects = (isSystemSideEffect: boolean | undefined) => {
+ const relatedFlatEntityMaps = createEmptyAllFlatEntityMaps();
+
+ if (isDefined(isSystemSideEffect)) {
+ relatedFlatEntityMaps.flatWorkflowVersionMaps.byUniversalIdentifier[
+ VERSION_ID
+ ] = {
+ universalIdentifier: VERSION_ID,
+ isSystemSideEffect,
+ } as FlatWorkflowVersion;
+ }
+
+ return buildWorkflowVersionDeleteSideEffects({
+ flatEntity: deletedWorkflow,
+ allFlatEntityOperationRecordByMetadataName: {},
+ relatedFlatEntityMaps,
+ context: {
+ buildOptions: {
+ isSystemBuild: false,
+ applicationUniversalIdentifier: APPLICATION_ID,
+ },
+ },
+ });
+};
+
+describe('buildWorkflowVersionDeleteSideEffects', () => {
+ it('deletes the managed version of a deleted application workflow', () => {
+ expect(buildDeleteSideEffects(true)).toMatchObject({
+ status: 'success',
+ operations: {
+ workflowVersion: {
+ flatEntityToDelete: {
+ [VERSION_ID]: { universalIdentifier: VERSION_ID },
+ },
+ },
+ },
+ });
+ });
+
+ it('leaves workflows without a managed version alone', () => {
+ expect(buildDeleteSideEffects(undefined)).toEqual({ status: 'noop' });
+ expect(buildDeleteSideEffects(false)).toEqual({ status: 'noop' });
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/__tests__/build-workflow-version-side-effects.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/__tests__/build-workflow-version-side-effects.util.spec.ts
new file mode 100644
index 00000000000..e0359122193
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/__tests__/build-workflow-version-side-effects.util.spec.ts
@@ -0,0 +1,226 @@
+import { buildWorkflowVersionSideEffects } from 'src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/build-workflow-version-side-effects.util';
+import { validateApplicationWorkflowVersion } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/validate-application-workflow-version.util';
+import {
+ getWorkflowVersionUniversalIdentifier,
+ type WorkflowManifest,
+} from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { fromWorkflowManifestToUniversalFlatWorkflowOrThrow } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util';
+import { buildAllFlatEntityOperationRecordByMetadataNameFromFromTo } from 'src/engine/core-modules/application/application-manifest/utils/build-all-flat-entity-operation-record-by-metadata-name-from-from-to.util';
+import { createEmptyAllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-all-flat-entity-maps.constant';
+import { type FlatWorkflow } from 'src/engine/metadata-modules/flat-workflow/types/flat-workflow.type';
+import { flatEntityToScalarFlatEntity } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/flat-entity-to-scalar-flat-entity.util';
+
+const APPLICATION_ID = '11111111-1111-4111-8111-111111111111';
+const WORKFLOW_ID = '22222222-2222-4222-8222-222222222222';
+const VERSION_ID = getWorkflowVersionUniversalIdentifier({
+ applicationUniversalIdentifier: APPLICATION_ID,
+ workflowUniversalIdentifier: WORKFLOW_ID,
+});
+const TRIGGER_ID = '44444444-4444-4444-8444-444444444444';
+const STEP_ID = '55555555-5555-4555-8555-555555555555';
+const buildOptions = {
+ isSystemBuild: false,
+ applicationUniversalIdentifier: APPLICATION_ID,
+ inferDeletionFromMissingEntities: true as const,
+};
+const manifest: WorkflowManifest = {
+ universalIdentifier: WORKFLOW_ID,
+ name: 'Application workflow',
+ version: {
+ trigger: {
+ universalIdentifier: TRIGGER_ID,
+ type: 'MANUAL',
+ nextStepIds: [STEP_ID],
+ },
+ steps: [
+ {
+ universalIdentifier: STEP_ID,
+ name: 'Finish',
+ type: 'EMPTY',
+ input: {},
+ nextStepIds: [],
+ },
+ ],
+ },
+};
+
+const convert = (
+ definition = manifest,
+ existing = createEmptyAllFlatEntityMaps(),
+ now = '2026-09-29T10:00:00.000Z',
+) => {
+ const workflow = fromWorkflowManifestToUniversalFlatWorkflowOrThrow({
+ manifest: definition,
+ applicationUniversalIdentifier: APPLICATION_ID,
+ now,
+ logicFunctionIdByUniversalIdentifier: new Map(),
+ existingWorkflow:
+ existing.flatWorkflowMaps.byUniversalIdentifier[WORKFLOW_ID],
+ existingVersion:
+ existing.flatWorkflowVersionMaps.byUniversalIdentifier[VERSION_ID],
+ });
+ const version = workflow.flatUniversalWorkflowVersion;
+ if (!isDefined(version)) {
+ throw new Error('Expected managed version');
+ }
+ return { workflow, version };
+};
+
+const persisted = ({ workflow, version }: ReturnType<typeof convert>) => {
+ const maps = createEmptyAllFlatEntityMaps();
+ const { flatUniversalWorkflowVersion: _payload, ...storedWorkflow } =
+ workflow;
+ maps.flatWorkflowMaps.byUniversalIdentifier[WORKFLOW_ID] = {
+ ...storedWorkflow,
+ workspaceId: APPLICATION_ID,
+ applicationId: APPLICATION_ID,
+ };
+ maps.flatWorkflowVersionMaps.byUniversalIdentifier[VERSION_ID] = {
+ ...version,
+ workspaceId: APPLICATION_ID,
+ applicationId: APPLICATION_ID,
+ };
+ return maps;
+};
+
+const diff = (
+ workflow: ReturnType<typeof convert>['workflow'],
+ from = createEmptyAllFlatEntityMaps(),
+) => {
+ const to = createEmptyAllFlatEntityMaps();
+ to.flatWorkflowMaps.byUniversalIdentifier[WORKFLOW_ID] =
+ workflow as FlatWorkflow;
+ return buildAllFlatEntityOperationRecordByMetadataNameFromFromTo({
+ fromAllFlatEntityMaps: from,
+ toAllUniversalFlatEntityMaps: to,
+ buildOptions,
+ });
+};
+
+const expand = (
+ workflow: ReturnType<typeof convert>['workflow'],
+ from = createEmptyAllFlatEntityMaps(),
+) => {
+ const operations = diff(workflow, from);
+ if (!isDefined(operations.workflow)) {
+ return {};
+ }
+ const result = buildWorkflowVersionSideEffects({
+ flatEntity: workflow,
+ allFlatEntityOperationRecordByMetadataName: operations,
+ relatedFlatEntityMaps: from,
+ context: { buildOptions },
+ });
+ if (result.status !== 'success') {
+ throw new Error(JSON.stringify(result));
+ }
+ return result.operations;
+};
+
+describe('application workflow version side effects', () => {
+ it('creates a managed companion and excludes its payload from scalar storage', () => {
+ const { workflow, version } = convert();
+ const operations = expand(workflow);
+ expect(
+ operations.workflowVersion?.flatEntityToCreate?.[VERSION_ID],
+ ).toEqual(version);
+ expect(version.isSystemSideEffect).toBe(true);
+ expect(
+ flatEntityToScalarFlatEntity({
+ metadataName: 'workflow',
+ flatEntity: workflow as FlatWorkflow,
+ }),
+ ).not.toHaveProperty('flatUniversalWorkflowVersion');
+ });
+
+ it('updates the same version for a graph-only change without mutating the previous definition', () => {
+ const before = convert();
+ const changed = structuredClone(manifest);
+ changed.version.steps[0].name = 'Updated step';
+ const after = convert(changed, persisted(before));
+ const operations = expand(after.workflow, persisted(before));
+ expect(after.workflow.versionDefinitionHash).not.toBe(
+ before.workflow.versionDefinitionHash,
+ );
+ expect(
+ operations.workflowVersion?.flatEntityToUpdate?.[VERSION_ID],
+ ).toMatchObject({
+ id: before.version.id,
+ steps: [{ name: 'Updated step' }],
+ });
+ expect(
+ diff(after.workflow, persisted(before)).workflowVersion,
+ ).toBeUndefined();
+ expect(before.version.steps?.[0].name).toBe('Finish');
+ });
+
+ it('does not generate operations when only sync timestamps change', () => {
+ const before = convert();
+ const after = convert(
+ manifest,
+ persisted(before),
+ '2026-09-30T10:00:00.000Z',
+ );
+ expect(after.workflow.versionDefinitionHash).toBe(
+ before.workflow.versionDefinitionHash,
+ );
+ expect(expand(after.workflow, persisted(before))).toEqual({});
+ });
+
+ it('adopts the existing POC companion in place without inferring its deletion', () => {
+ const before = convert();
+ const existing = persisted(before);
+ existing.flatWorkflowMaps.byUniversalIdentifier[
+ WORKFLOW_ID
+ ]!.versionDefinitionHash = null;
+ existing.flatWorkflowVersionMaps.byUniversalIdentifier[
+ VERSION_ID
+ ]!.isSystemSideEffect = false;
+ const after = convert(manifest, existing);
+ const operations = expand(after.workflow, existing);
+ expect(
+ operations.workflowVersion?.flatEntityToUpdate?.[VERSION_ID],
+ ).toMatchObject({ id: before.version.id, isSystemSideEffect: true });
+ expect(diff(after.workflow, existing).workflowVersion).toBeUndefined();
+ });
+
+ it('leaves API workflow operations without a version payload unchanged', () => {
+ const { workflow } = convert();
+ const { flatUniversalWorkflowVersion: _payload, ...apiWorkflow } = workflow;
+ expect(
+ buildWorkflowVersionSideEffects({
+ flatEntity: apiWorkflow,
+ allFlatEntityOperationRecordByMetadataName: {},
+ relatedFlatEntityMaps: createEmptyAllFlatEntityMaps(),
+ context: { buildOptions },
+ }),
+ ).toEqual({ status: 'noop' });
+ });
+});
+
+const validate = (version: ReturnType<typeof convert>['version']) => ({
+ errors: validateApplicationWorkflowVersion({ version }),
+});
+
+describe('managed workflow version validation', () => {
+ it('accepts a valid companion and accumulates missing edge and self-cycle errors', () => {
+ const definition = convert();
+ expect(validate(definition.version).errors).toEqual([]);
+ const invalid = structuredClone(manifest);
+ invalid.version.trigger.nextStepIds = [APPLICATION_ID];
+ invalid.version.steps[0].nextStepIds = [STEP_ID];
+ const { version } = convert(invalid);
+ expect(validate(version).errors.length).toBeGreaterThan(1);
+ });
+
+ it('validates a managed definition but leaves API definitions unchanged', () => {
+ const definition = convert();
+ const invalid = { ...definition.version, triggers: null };
+ expect(validate(invalid).errors).not.toEqual([]);
+ expect(validate({ ...invalid, isSystemSideEffect: false }).errors).toEqual(
+ [],
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/build-workflow-version-delete-side-effects.util.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/build-workflow-version-delete-side-effects.util.ts
new file mode 100644
index 00000000000..de8241dae71
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/build-workflow-version-delete-side-effects.util.ts
@@ -0,0 +1,33 @@
+import { getWorkflowVersionUniversalIdentifier } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type BuildSideEffectsArgs } from 'src/engine/metadata-modules/metadata-side-effect/interfaces/base-metadata-side-effect-handler.service';
+import { type MetadataSideEffectResult } from 'src/engine/metadata-modules/metadata-side-effect/types/metadata-side-effect-result.type';
+
+export const buildWorkflowVersionDeleteSideEffects = ({
+ flatEntity,
+ relatedFlatEntityMaps,
+}: BuildSideEffectsArgs<'workflow'>): MetadataSideEffectResult => {
+ const universalIdentifier = getWorkflowVersionUniversalIdentifier({
+ applicationUniversalIdentifier: flatEntity.applicationUniversalIdentifier,
+ workflowUniversalIdentifier: flatEntity.universalIdentifier,
+ });
+
+ const managedVersion =
+ relatedFlatEntityMaps.flatWorkflowVersionMaps.byUniversalIdentifier[
+ universalIdentifier
+ ];
+
+ if (!isDefined(managedVersion) || !managedVersion.isSystemSideEffect) {
+ return { status: 'noop' };
+ }
+
+ return {
+ status: 'success',
+ operations: {
+ workflowVersion: {
+ flatEntityToDelete: { [universalIdentifier]: managedVersion },
+ },
+ },
+ };
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/build-workflow-version-side-effects.util.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/build-workflow-version-side-effects.util.ts
new file mode 100644
index 00000000000..02d74bfd34a
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/workflow/utils/build-workflow-version-side-effects.util.ts
@@ -0,0 +1,39 @@
+import { getWorkflowVersionUniversalIdentifier } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type BuildSideEffectsArgs } from 'src/engine/metadata-modules/metadata-side-effect/interfaces/base-metadata-side-effect-handler.service';
+import { type MetadataSideEffectResult } from 'src/engine/metadata-modules/metadata-side-effect/types/metadata-side-effect-result.type';
+
+export const buildWorkflowVersionSideEffects = ({
+ flatEntity,
+ relatedFlatEntityMaps,
+}: BuildSideEffectsArgs<'workflow'>): MetadataSideEffectResult => {
+ const version = flatEntity.flatUniversalWorkflowVersion;
+
+ if (!isDefined(version)) {
+ return { status: 'noop' };
+ }
+
+ const universalIdentifier = getWorkflowVersionUniversalIdentifier({
+ applicationUniversalIdentifier: flatEntity.applicationUniversalIdentifier,
+ workflowUniversalIdentifier: flatEntity.universalIdentifier,
+ });
+
+ const existingVersion =
+ relatedFlatEntityMaps.flatWorkflowVersionMaps.byUniversalIdentifier[
+ universalIdentifier
+ ];
+
+ return {
+ status: 'success',
+ operations: {
+ workflowVersion: {
+ [isDefined(existingVersion)
+ ? 'flatEntityToUpdate'
+ : 'flatEntityToCreate']: {
+ [universalIdentifier]: { ...version, universalIdentifier },
+ },
+ },
+ },
+ };
+};
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts
index d072dc6cbd0..c6a4d6471d6 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts
@@ -499,7 +499,7 @@ export const STANDARD_COMMAND_MENU_ITEMS = {
),
availabilityType: CommandMenuItemAvailabilityType.RECORD_SELECTION,
conditionalAvailabilityExpression:
- 'numberOfSelectedRecords == 1 and (everyEquals(selectedRecords, "currentVersion.status", "ACTIVE") or includesEvery(selectedRecords, "statuses", "ACTIVE")) and noneDefined(selectedRecords, "deletedAt")',
+ 'numberOfSelectedRecords == 1 and (everyEquals(selectedRecords, "currentVersion.status", "ACTIVE") or includesEvery(selectedRecords, "statuses", "ACTIVE")) and noneDefined(selectedRecords, "deletedAt") and noneEquals(selectedRecords, "recordPermissions.canUpdate", false)',
availabilityObjectMetadataUniversalIdentifier:
STANDARD_OBJECTS.workflow.universalIdentifier,
frontComponentUniversalIdentifier: null,
@@ -602,7 +602,7 @@ export const STANDARD_COMMAND_MENU_ITEMS = {
),
availabilityType: CommandMenuItemAvailabilityType.RECORD_SELECTION,
conditionalAvailabilityExpression:
- 'pageType == "RECORD_PAGE" and everyDefined(selectedRecords, "currentVersion.trigger") and everyDefined(selectedRecords, "currentVersion.steps") and every(selectedRecords, "currentVersion.steps.length") and noneDefined(selectedRecords, "deletedAt")',
+ 'pageType == "RECORD_PAGE" and everyDefined(selectedRecords, "currentVersion.trigger") and everyDefined(selectedRecords, "currentVersion.steps") and every(selectedRecords, "currentVersion.steps.length") and noneDefined(selectedRecords, "deletedAt") and noneEquals(selectedRecords, "recordPermissions.canUpdate", false)',
availabilityObjectMetadataUniversalIdentifier:
STANDARD_OBJECTS.workflow.universalIdentifier,
frontComponentUniversalIdentifier: null,
@@ -622,7 +622,7 @@ export const STANDARD_COMMAND_MENU_ITEMS = {
),
availabilityType: CommandMenuItemAvailabilityType.RECORD_SELECTION,
conditionalAvailabilityExpression:
- 'everyDefined(selectedRecords, "currentVersion") and noneDefined(selectedRecords, "deletedAt")',
+ 'everyDefined(selectedRecords, "currentVersion") and noneDefined(selectedRecords, "deletedAt") and noneEquals(selectedRecords, "recordPermissions.canUpdate", false)',
availabilityObjectMetadataUniversalIdentifier:
STANDARD_OBJECTS.workflow.universalIdentifier,
frontComponentUniversalIdentifier: null,
@@ -645,7 +645,7 @@ export const STANDARD_COMMAND_MENU_ITEMS = {
),
availabilityType: CommandMenuItemAvailabilityType.RECORD_SELECTION,
conditionalAvailabilityExpression:
- 'numberOfSelectedRecords == 1 and everyEquals(selectedRecords, "visibility", "WORKSPACE") and every(selectedRecords, "canChangeVisibility") and noneDefined(selectedRecords, "deletedAt")',
+ 'numberOfSelectedRecords == 1 and everyEquals(selectedRecords, "visibility", "WORKSPACE") and every(selectedRecords, "canChangeVisibility") and noneDefined(selectedRecords, "deletedAt") and noneEquals(selectedRecords, "recordPermissions.canUpdate", false)',
availabilityObjectMetadataUniversalIdentifier:
STANDARD_OBJECTS.workflow.universalIdentifier,
frontComponentUniversalIdentifier: null,
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service.ts
index 8d38daee749..4b54b6804d7 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service.ts
@@ -1,9 +1,11 @@
import { Injectable } from '@nestjs/common';
import {
+ ALL_METADATA_NAME,
AllMetadataName,
WorkspaceMigrationV2ExceptionCode,
} from 'twenty-shared/metadata';
+import { isDefined } from 'twenty-shared/utils';
import { LoggerService } from 'src/engine/core-modules/logger/logger.service';
import { WORKSPACE_MIGRATION_ACTION_COUNT_BUCKET_BOUNDARIES } from 'src/engine/core-modules/metrics/constants/workspace-migration-action-count-bucket-boundaries.constant';
@@ -47,6 +49,7 @@ type ValidateBuildAndRunWorkspaceMigrationFromRecordArgs = {
allFlatEntityOperationRecordByMetadataName: AllFlatEntityOperationRecordByMetadataName;
isSystemBuild?: boolean;
applicationUniversalIdentifier: string;
+ idByUniversalIdentifierByMetadataName?: IdByUniversalIdentifierByMetadataName;
dryRun?: boolean;
};
@@ -62,6 +65,7 @@ type ComputeAndRunWorkspaceMigrationFromResolvedOperationsArgs = {
allFlatEntityOperationRecordByMetadataName: AllFlatEntityOperationRecordByMetadataName;
isSystemBuild: boolean;
applicationUniversalIdentifier: string;
+ providedIdByUniversalIdentifierByMetadataName?: IdByUniversalIdentifierByMetadataName;
dryRun?: boolean;
} & FlatEntityMapsBundle;
@@ -281,6 +285,7 @@ export class WorkspaceMigrationValidateBuildAndRunService {
workspaceId,
isSystemBuild = false,
applicationUniversalIdentifier,
+ idByUniversalIdentifierByMetadataName,
dryRun,
skipSideEffectExpandEngine,
}: ValidateBuildAndRunWorkspaceMigrationFromRecordInternalArgs): Promise<
@@ -332,6 +337,8 @@ export class WorkspaceMigrationValidateBuildAndRunService {
workspaceId,
isSystemBuild,
applicationUniversalIdentifier,
+ providedIdByUniversalIdentifierByMetadataName:
+ idByUniversalIdentifierByMetadataName,
dryRun,
flatApplicationMaps,
allRelatedFlatEntityMaps,
@@ -344,6 +351,7 @@ export class WorkspaceMigrationValidateBuildAndRunService {
workspaceId,
isSystemBuild,
applicationUniversalIdentifier,
+ providedIdByUniversalIdentifierByMetadataName,
dryRun,
flatApplicationMaps,
allRelatedFlatEntityMaps,
@@ -371,6 +379,21 @@ export class WorkspaceMigrationValidateBuildAndRunService {
},
);
+ const mergedIdByUniversalIdentifierByMetadataName: IdByUniversalIdentifierByMetadataName =
+ { ...idByUniversalIdentifierByMetadataName };
+
+ for (const metadataName of Object.values(ALL_METADATA_NAME)) {
+ const providedIdByUniversalIdentifier =
+ providedIdByUniversalIdentifierByMetadataName?.[metadataName];
+
+ if (isDefined(providedIdByUniversalIdentifier)) {
+ mergedIdByUniversalIdentifierByMetadataName[metadataName] = {
+ ...providedIdByUniversalIdentifier,
+ ...idByUniversalIdentifierByMetadataName[metadataName],
+ };
+ }
+ }
+
return await this.validateBuildAndRunWorkspaceMigrationFromTo({
buildOptions: {
isSystemBuild,
@@ -381,7 +404,8 @@ export class WorkspaceMigrationValidateBuildAndRunService {
workspaceId,
dependencyAllFlatEntityMaps,
additionalCacheDataMaps,
- idByUniversalIdentifierByMetadataName,
+ idByUniversalIdentifierByMetadataName:
+ mergedIdByUniversalIdentifierByMetadataName,
dryRun,
});
}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-workflow.type.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-workflow.type.ts
index 49d1486b740..46758050604 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-workflow.type.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-workflow.type.ts
@@ -1,7 +1,10 @@
+import { type UniversalFlatWorkflowVersion } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-workflow-version.type';
import { type WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';
import { type UniversalFlatEntityFrom } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-entity-from.type';
export type UniversalFlatWorkflow = UniversalFlatEntityFrom<
WorkflowEntity,
'workflow'
->;
+> & {
+ flatUniversalWorkflowVersion?: UniversalFlatWorkflowVersion & { id: string };
+};
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-workflow-version-validator.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-workflow-version-validator.service.ts
index e52bfc08106..4c11de3ef5d 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-workflow-version-validator.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-workflow-version-validator.service.ts
@@ -10,6 +10,7 @@ import { type FailedFlatEntityValidation } from 'src/engine/workspace-manager/wo
import { getEmptyFlatEntityValidationError } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/utils/get-flat-entity-validation-error.util';
import { type FlatEntityUpdateValidationArgs } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/universal-flat-entity-update-validation-args.type';
import { type UniversalFlatEntityValidationArgs } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/universal-flat-entity-validation-args.type';
+import { validateApplicationWorkflowVersion } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/validate-application-workflow-version.util';
@Injectable()
export class FlatWorkflowVersionValidatorService {
@@ -42,6 +43,10 @@ export class FlatWorkflowVersionValidatorService {
});
}
+ validationResult.errors.push(
+ ...validateApplicationWorkflowVersion({ version: flatWorkflowVersion }),
+ );
+
return validationResult;
}
@@ -79,6 +84,7 @@ export class FlatWorkflowVersionValidatorService {
public validateFlatWorkflowVersionUpdate({
universalIdentifier,
+ flatEntityUpdate,
optimisticFlatEntityMapsAndRelatedFlatEntityMaps: {
flatWorkflowVersionMaps: optimisticFlatWorkflowVersionMaps,
},
@@ -104,8 +110,16 @@ export class FlatWorkflowVersionValidatorService {
message: t`Workflow version not found`,
userFriendlyMessage: msg`Workflow version not found`,
});
+
+ return validationResult;
}
+ validationResult.errors.push(
+ ...validateApplicationWorkflowVersion({
+ version: { ...existingWorkflowVersion, ...flatEntityUpdate },
+ }),
+ );
+
return validationResult;
}
}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/validate-application-workflow-version.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/validate-application-workflow-version.util.ts
new file mode 100644
index 00000000000..f1e9c1e4581
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/utils/validate-application-workflow-version.util.ts
@@ -0,0 +1,68 @@
+import { msg } from '@lingui/core/macro';
+import { isDefined } from 'twenty-shared/utils';
+import {
+ buildWorkflowGraph,
+ validateWorkflowGraph,
+ validateWorkflowExecutionPaths,
+ validateWorkflowVariableReferences,
+} from 'twenty-shared/workflow';
+
+import { CoreWorkflowMetadataExceptionCode } from 'src/engine/core-modules/workflow/exceptions/core-workflow-metadata.exception';
+import { type UniversalFlatWorkflowVersion } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-workflow-version.type';
+import { type FlatEntityValidationError } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/types/failed-flat-entity-validation.type';
+
+export const validateApplicationWorkflowVersion = ({
+ version,
+}: {
+ version: UniversalFlatWorkflowVersion;
+}): FlatEntityValidationError[] => {
+ if (!version.isSystemSideEffect) {
+ return [];
+ }
+
+ const trigger = version.triggers?.[0];
+ const steps = version.steps ?? [];
+ const messages: string[] = [];
+
+ if (
+ !isDefined(trigger) ||
+ version.triggers?.length !== 1 ||
+ trigger.type !== 'MANUAL'
+ ) {
+ messages.push('Application workflows require one manual trigger');
+ } else {
+ const identities = [
+ version.universalIdentifier,
+ 'universalIdentifier' in trigger
+ ? trigger.universalIdentifier
+ : undefined,
+ ...steps.map((step) => step.id),
+ ].filter(isDefined);
+ if (new Set(identities).size !== identities.length) {
+ messages.push(
+ 'Version, trigger and steps must have distinct universal identifiers',
+ );
+ }
+ const content = { trigger, steps };
+ const graph = buildWorkflowGraph(content);
+ messages.push(
+ ...[
+ ...validateWorkflowGraph({ workflow: content, graph }),
+ ...validateWorkflowExecutionPaths({ workflow: content, graph }),
+ ...validateWorkflowVariableReferences({
+ workflow: content,
+ graph,
+ stepsById: new Map(steps.map((step) => [step.id, step])),
+ }),
+ ]
+ .filter((issue) => issue.severity === 'error')
+ .map((issue) => issue.message),
+ );
+ }
+
+ return messages.map((message) => ({
+ code: CoreWorkflowMetadataExceptionCode.INVALID_WORKFLOW_VERSION_DEFINITION,
+ message,
+ userFriendlyMessage: msg`The application workflow definition is invalid.`,
+ }));
+};
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/__tests__/get-metadata-names-to-load-for-workspace-migration.util.spec.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/__tests__/get-metadata-names-to-load-for-workspace-migration.util.spec.ts
new file mode 100644
index 00000000000..29de0b03948
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/__tests__/get-metadata-names-to-load-for-workspace-migration.util.spec.ts
@@ -0,0 +1,9 @@
+import { getMetadataNamesToLoadForWorkspaceMigration } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/get-metadata-names-to-load-for-workspace-migration.util';
+
+describe('getMetadataNamesToLoadForWorkspaceMigration', () => {
+ it('loads no other metadata for workflow version writes', () => {
+ expect(
+ getMetadataNamesToLoadForWorkspaceMigration(['workflowVersion']),
+ ).toEqual(['workflowVersion']);
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-schema/utils/__tests__/compute-ai-agent-output-schema.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-schema/utils/__tests__/compute-ai-agent-output-schema.util.spec.ts
new file mode 100644
index 00000000000..c7109124a05
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-schema/utils/__tests__/compute-ai-agent-output-schema.util.spec.ts
@@ -0,0 +1,11 @@
+import { type AgentResponseFormat } from 'twenty-shared/ai';
+
+import { computeAiAgentOutputSchema } from 'src/modules/workflow/workflow-builder/workflow-schema/utils/compute-ai-agent-output-schema.util';
+
+describe('computeAiAgentOutputSchema', () => {
+ it('returns no fields for a saved JSON format without properties', () => {
+ const responseFormat = { type: 'json', schema: {} } as AgentResponseFormat;
+
+ expect(computeAiAgentOutputSchema(responseFormat)).toEqual({});
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-schema/utils/compute-ai-agent-output-schema.util.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-schema/utils/compute-ai-agent-output-schema.util.ts
new file mode 100644
index 00000000000..d09711aac73
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-schema/utils/compute-ai-agent-output-schema.util.ts
@@ -0,0 +1,37 @@
+import { type AgentResponseFormat } from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
+import { type BaseOutputSchemaV2 } from 'twenty-shared/workflow';
+
+import { generateFakeValue } from 'src/engine/utils/generate-fake-value';
+
+export const computeAiAgentOutputSchema = (
+ responseFormat?: AgentResponseFormat | null,
+): BaseOutputSchemaV2 => {
+ if (responseFormat?.type !== 'json') {
+ return {
+ response: {
+ label: 'Response',
+ isLeaf: true,
+ type: 'string',
+ value: 'Response of the agent',
+ },
+ };
+ }
+
+ return Object.fromEntries(
+ Object.entries(responseFormat.schema.properties ?? {}).map(
+ ([name, property]) => [
+ name,
+ {
+ isLeaf: true,
+ type: property.type,
+ label: name,
+ ...(isDefined(property.description)
+ ? { description: property.description }
+ : {}),
+ value: generateFakeValue(property.type),
+ },
+ ],
+ ),
+ );
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-schema/workflow-schema.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-schema/workflow-schema.workspace-service.ts
index c4ec5df336b..da742c65ab5 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-schema/workflow-schema.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-schema/workflow-schema.workspace-service.ts
@@ -1,3 +1,4 @@
+import { computeAiAgentOutputSchema } from 'src/modules/workflow/workflow-builder/workflow-schema/utils/compute-ai-agent-output-schema.util';
import { Injectable, Logger } from '@nestjs/common';
import { isString } from '@sniptt/guards';
@@ -33,7 +34,6 @@ import { generateFakeValue } from 'src/engine/utils/generate-fake-value';
import { WorkflowCommonWorkspaceService } from 'src/modules/workflow/common/workspace-services/workflow-common.workspace-service';
import { DEFAULT_ITERATOR_CURRENT_ITEM } from 'src/modules/workflow/workflow-builder/workflow-schema/constants/default-iterator-current-item.const';
import {
- type BaseOutputSchema,
Leaf,
Node,
type OutputSchema,
@@ -415,17 +415,8 @@ export class WorkflowSchemaWorkspaceService {
agentId?: string;
workspaceId: string;
}): Promise<OutputSchema> {
- const textResponseOutputSchema: OutputSchema = {
- response: {
- label: 'Response',
- isLeaf: true,
- type: 'string',
- value: 'Response of the agent',
- },
- };
-
if (!isDefined(agentId)) {
- return textResponseOutputSchema;
+ return computeAiAgentOutputSchema();
}
const { flatAgentMaps } =
@@ -441,28 +432,7 @@ export class WorkflowSchemaWorkspaceService {
flatEntityMaps: flatAgentMaps,
});
- const responseFormat = flatAgent?.responseFormat;
-
- if (responseFormat?.type !== 'json') {
- return textResponseOutputSchema;
- }
-
- return Object.entries(responseFormat.schema.properties || {}).reduce(
- (outputSchema, [propertyName, property]) => {
- outputSchema[propertyName] = {
- isLeaf: true,
- type: property.type,
- label: propertyName,
- ...(isDefined(property.description)
- ? { description: property.description }
- : {}),
- value: generateFakeValue(property.type),
- };
-
- return outputSchema;
- },
- {} as BaseOutputSchema,
- );
+ return computeAiAgentOutputSchema(flatAgent?.responseFormat);
}
private async computeFormActionOutputSchema({
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/successful-sync-application-workflows.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/successful-sync-application-workflows.integration-spec.ts
new file mode 100644
index 00000000000..cb522207e6c
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/application/successful-sync-application-workflows.integration-spec.ts
@@ -0,0 +1,348 @@
+import { buildDefaultObjectManifest } from 'test/integration/metadata/suites/application/utils/build-default-object-manifest.util';
+import { FieldMetadataType, FeatureFlagKey } from 'twenty-shared/types';
+import { updateFeatureFlag } from 'test/integration/metadata/suites/utils/update-feature-flag.util';
+import { randomUUID } from 'node:crypto';
+import { type Manifest } from 'twenty-shared/application';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+
+import { type ApplicationManifestMigrationService } from 'src/engine/core-modules/application/application-manifest/application-manifest-migration.service';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+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 { type WorkflowRunWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
+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';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';
+import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+
+const REFERENCE_APP_ID = randomUUID();
+const REFERENCE_ROLE_ID = randomUUID();
+const REFERENCE_OBJECT_ID = randomUUID();
+const REFERENCE_FIELD_ID = randomUUID();
+const REFERENCE_WORKFLOW_ID = randomUUID();
+const REFERENCE_STEP_ID = randomUUID();
+const APP_ID = randomUUID();
+const ROLE_ID = randomUUID();
+const WORKFLOW_ID = randomUUID();
+const STEP_ID = randomUUID();
+const RECORD_STEP_ID = randomUUID();
+const DELAY_STEP_ID = randomUUID();
+const FUNCTION_ID = randomUUID();
+const WORKSPACE_ID = SEED_APPLE_WORKSPACE_ID;
+const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);
+const MANIFEST: Manifest = buildBaseManifest({
+ appId: APP_ID,
+ roleId: ROLE_ID,
+ overrides: {
+ logicFunctions: [
+ {
+ universalIdentifier: FUNCTION_ID,
+ name: 'Application workflow greeting',
+ sourceHandlerPath: 'greet.ts',
+ builtHandlerPath: 'greet.mjs',
+ builtHandlerChecksum: '',
+ handlerName: 'handler',
+ workflowActionTriggerSettings: { label: 'Greet', icon: 'IconHandStop' },
+ },
+ ],
+ workflows: [
+ {
+ universalIdentifier: WORKFLOW_ID,
+ name: 'Application workflow',
+ version: {
+ trigger: {
+ universalIdentifier: randomUUID(),
+ type: 'MANUAL',
+ nextStepIds: [STEP_ID],
+ },
+ steps: [
+ {
+ universalIdentifier: STEP_ID,
+ name: 'Greet',
+ type: 'LOGIC_FUNCTION',
+ logicFunctionUniversalIdentifier: FUNCTION_ID,
+ input: { greeting: 'Before' },
+ nextStepIds: [RECORD_STEP_ID],
+ },
+ {
+ universalIdentifier: RECORD_STEP_ID,
+ name: 'Create company',
+ type: 'CREATE_RECORD',
+ input: {
+ objectUniversalIdentifier:
+ STANDARD_OBJECTS.company.universalIdentifier,
+ objectRecord: { name: 'Workflow test company' },
+ },
+ nextStepIds: [DELAY_STEP_ID],
+ },
+ {
+ universalIdentifier: DELAY_STEP_ID,
+ name: 'Wait',
+ type: 'DELAY',
+ input: { delayType: 'DURATION', duration: { seconds: 1 } },
+ nextStepIds: [],
+ },
+ ],
+ },
+ },
+ {
+ universalIdentifier: REFERENCE_WORKFLOW_ID,
+ name: 'Workflow referencing another app',
+ version: {
+ trigger: {
+ universalIdentifier: randomUUID(),
+ type: 'MANUAL',
+ nextStepIds: [REFERENCE_STEP_ID],
+ },
+ steps: [
+ {
+ universalIdentifier: REFERENCE_STEP_ID,
+ name: 'Create external record',
+ type: 'CREATE_RECORD',
+ input: {
+ objectUniversalIdentifier: REFERENCE_OBJECT_ID,
+ objectRecord: { name: 'External record' },
+ },
+ nextStepIds: [],
+ },
+ ],
+ },
+ },
+ ],
+ },
+});
+
+const findDefinitions = () =>
+ globalThis.testDataSource.query(
+ `SELECT w.id AS "workflowId", w."workspaceWorkflowId", w."versionDefinitionHash", w."lastPublishedCoreWorkflowVersionId", v.id AS "versionId", v."workspaceWorkflowVersionId", v."isSystemSideEffect", v.status, v.steps, f.id AS "functionId"
+ FROM core.workflow w
+ JOIN core."workflowVersion" v ON v."coreWorkflowId" = w.id
+ JOIN core."logicFunction" f ON f."applicationId" = w."applicationId" AND f."universalIdentifier" = $3
+ WHERE w."workspaceId" = $1 AND w."universalIdentifier" = $2`,
+ [WORKSPACE_ID, WORKFLOW_ID, FUNCTION_ID],
+ );
+
+const runVersion = async (coreWorkflowVersionId: string): Promise<string> => {
+ const response = await workflowGraphqlRequest(
+ 'mutation Run($input: RunCoreWorkflowVersionInput!) { runCoreWorkflowVersion(input: $input) { workflowRunId } }',
+ { input: { coreWorkflowVersionId } },
+ );
+ expect(response.body.errors).toBeUndefined();
+ return response.body.data.runCoreWorkflowVersion.workflowRunId;
+};
+
+const findRun = async (runId: string): Promise<WorkflowRunWorkspaceEntity> => {
+ const [run] = await globalThis.testDataSource.query(
+ `SELECT * FROM "${SCHEMA}"."workflowRun" WHERE id = $1`,
+ [runId],
+ );
+ return run;
+};
+
+describe('application-owned core workflows', () => {
+ beforeAll(async () => {
+ await updateFeatureFlag({
+ featureFlag: FeatureFlagKey.IS_APPLICATION_WORKFLOWS_ENABLED,
+ value: true,
+ expectToFail: false,
+ });
+ await setupApplicationForSync({
+ applicationUniversalIdentifier: REFERENCE_APP_ID,
+ name: 'Workflow referenced application',
+ description: 'Owns an object used by another app workflow',
+ sourcePath: 'workflow-referenced-app',
+ });
+ await syncApplication({
+ manifest: buildBaseManifest({
+ appId: REFERENCE_APP_ID,
+ roleId: REFERENCE_ROLE_ID,
+ overrides: {
+ roles: [
+ {
+ universalIdentifier: REFERENCE_ROLE_ID,
+ label: 'Workflow referenced app role',
+ description: 'A test role',
+ },
+ ],
+ objects: [
+ buildDefaultObjectManifest({
+ applicationUniversalIdentifier: REFERENCE_APP_ID,
+ universalIdentifier: REFERENCE_OBJECT_ID,
+ nameSingular: 'workflowReferencedRecord',
+ namePlural: 'workflowReferencedRecords',
+ labelSingular: 'Workflow referenced record',
+ labelPlural: 'Workflow referenced records',
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ REFERENCE_FIELD_ID,
+ additionalFields: [
+ {
+ universalIdentifier: REFERENCE_FIELD_ID,
+ type: FieldMetadataType.TEXT,
+ name: 'name',
+ label: 'Name',
+ },
+ ],
+ }),
+ ],
+ },
+ }),
+ expectToFail: false,
+ });
+ await setupApplicationForSync({
+ applicationUniversalIdentifier: APP_ID,
+ name: 'Workflow POC integration',
+ description: 'Application workflow synchronization',
+ sourcePath: 'workflow-poc-integration',
+ });
+ jest.useRealTimers();
+ }, 60000);
+
+ afterAll(async () => {
+ await globalThis.testDataSource.query(
+ `DELETE FROM "${SCHEMA}"."workflowRun" WHERE "coreWorkflowId" IN (SELECT id FROM core.workflow WHERE "universalIdentifier" = $1 AND "workspaceId" = $2)`,
+ [WORKFLOW_ID, WORKSPACE_ID],
+ );
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: APP_ID,
+ });
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: REFERENCE_APP_ID,
+ });
+ await updateFeatureFlag({
+ featureFlag: FeatureFlagKey.IS_APPLICATION_WORKFLOWS_ENABLED,
+ value: false,
+ expectToFail: false,
+ });
+ jest.useFakeTimers();
+ });
+
+ it('installs, upgrades through additive pre-install sync, and protects saved runs and app-owned definitions', async () => {
+ const initial = await syncApplication({ manifest: MANIFEST });
+ expect(initial.errors).toBeUndefined();
+ const [referencingVersion] = await globalThis.testDataSource.query(
+ 'SELECT v.steps, v."isSystemSideEffect" FROM core.workflow w JOIN core."workflowVersion" v ON v."coreWorkflowId" = w.id WHERE w."workspaceId" = $1 AND w."universalIdentifier" = $2',
+ [WORKSPACE_ID, REFERENCE_WORKFLOW_ID],
+ );
+ expect(referencingVersion).toMatchObject({
+ isSystemSideEffect: true,
+ steps: [
+ {
+ settings: {
+ input: {
+ objectName: 'workflowReferencedRecord',
+ objectRecord: { name: 'External record' },
+ },
+ },
+ },
+ ],
+ });
+ const definitions = await findDefinitions();
+ expect(definitions).toHaveLength(1);
+ const [installed] = definitions;
+ expect(installed).toMatchObject({
+ status: 'ACTIVE',
+ isSystemSideEffect: true,
+ versionDefinitionHash: expect.any(String),
+ workspaceWorkflowId: null,
+ workspaceWorkflowVersionId: null,
+ lastPublishedCoreWorkflowVersionId: installed.versionId,
+ });
+ expect(installed.steps[0].settings.input).toEqual({
+ logicFunctionId: installed.functionId,
+ logicFunctionInput: { greeting: 'Before' },
+ });
+ expect(installed.steps[1].settings.input).toEqual({
+ objectName: 'company',
+ objectRecord: { name: 'Workflow test company' },
+ });
+ expect(installed.steps[2].settings.input).toEqual({
+ delayType: 'DURATION',
+ duration: { seconds: 1 },
+ });
+ const oldRunId = await runVersion(installed.versionId);
+ const oldRun = await findRun(oldRunId);
+ expect(oldRun.coreWorkflowId).toBe(installed.workflowId);
+ expect(oldRun.coreWorkflowVersionId).toBe(installed.versionId);
+ expect(oldRun.state?.flow?.steps).toEqual(installed.steps);
+
+ const [ownerFlatApplication] = await globalThis.testDataSource.query<
+ FlatApplication[]
+ >(
+ 'SELECT * FROM core.application WHERE "universalIdentifier" = $1 AND "workspaceId" = $2',
+ [APP_ID, WORKSPACE_ID],
+ );
+ expect(ownerFlatApplication).toBeDefined();
+ const migrationService =
+ getAppProviderByClassName<ApplicationManifestMigrationService>(
+ 'ApplicationManifestMigrationService',
+ );
+ await migrationService.syncPreInstallLogicFunctionFromManifest({
+ manifest: {
+ ...MANIFEST,
+ application: {
+ ...MANIFEST.application,
+ preInstallLogicFunction: { universalIdentifier: FUNCTION_ID },
+ },
+ },
+ workspaceId: WORKSPACE_ID,
+ ownerFlatApplication,
+ });
+ expect(await findDefinitions()).toEqual(definitions);
+ const unchanged = await syncApplication({ manifest: MANIFEST });
+ expect(unchanged.errors).toBeUndefined();
+ expect(unchanged.data.syncApplication.actions).toEqual([]);
+
+ const rename = await workflowGraphqlRequest(
+ 'mutation Rename($input: UpdateCoreWorkflowInput!) { updateCoreWorkflow(input: $input) { id } }',
+ {
+ input: { coreWorkflowId: installed.workflowId, name: 'Forbidden edit' },
+ },
+ );
+ expect(rename.body.errors).toBeDefined();
+ expect(JSON.stringify(rename.body.errors)).toContain('read-only');
+ const deletion = await workflowGraphqlRequest(
+ 'mutation Delete($input: DeleteCoreWorkflowsInput!) { deleteCoreWorkflows(input: $input) { id } }',
+ { input: { coreWorkflowIds: [installed.workflowId] } },
+ );
+ expect(deletion.body.errors).toBeDefined();
+ expect(JSON.stringify(deletion.body.errors)).toContain('read-only');
+
+ const changed = structuredClone(MANIFEST);
+ const changedStep = changed.workflows![0].version.steps[0];
+ if (changedStep.type !== 'LOGIC_FUNCTION') {
+ throw new Error('Expected a function step');
+ }
+ changedStep.input.greeting = 'After';
+ const upgrade = await syncApplication({ manifest: changed });
+ expect(upgrade.errors).toBeUndefined();
+ const updatedDefinitions = await findDefinitions();
+ expect(updatedDefinitions).toHaveLength(1);
+ const [updated] = updatedDefinitions;
+ expect(updated.workflowId).toBe(installed.workflowId);
+ expect(updated.versionId).toBe(installed.versionId);
+ expect(updated.versionDefinitionHash).not.toBe(
+ installed.versionDefinitionHash,
+ );
+ expect(updated.steps[0].settings.input.logicFunctionInput).toEqual({
+ greeting: 'After',
+ });
+ expect((await findRun(oldRunId)).state?.flow).toEqual(oldRun.state?.flow);
+ const newRunId = await runVersion(updated.versionId);
+ expect((await findRun(newRunId)).state?.flow?.steps).toEqual(updated.steps);
+
+ const missingWorkflow = { ...changed, workflows: [] };
+ const additive = await syncApplication({
+ manifest: missingWorkflow,
+ inferDeletionFromMissingEntities: false,
+ });
+ expect(additive.errors).toBeUndefined();
+ const removing = await syncApplication({
+ manifest: missingWorkflow,
+ expectToFail: true,
+ });
+ expect(removing.errors).toBeDefined();
+ expect(await findDefinitions()).toEqual(updatedDefinitions);
+ }, 90000);
+});
diff --git a/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts b/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
new file mode 100644
index 00000000000..7c74b6e9bdd
--- /dev/null
+++ b/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts
@@ -0,0 +1,123 @@
+/** @jest-environment node */
+
+import { isDefined } from '@/utils/validation/isDefined';
+
+import {
+ workflowManifestSchema,
+ type WorkflowManifest,
+} from '../workflowManifestType';
+
+const iteratorId = '44444444-4444-4444-8444-444444444444';
+const delayId = '55555555-5555-4555-8555-555555555555';
+const finishId = '66666666-6666-4666-8666-666666666666';
+const workflow: WorkflowManifest = {
+ universalIdentifier: '11111111-1111-4111-8111-111111111111',
+ name: 'Iterator validation',
+ version: {
+ trigger: {
+ universalIdentifier: '33333333-3333-4333-8333-333333333333',
+ type: 'MANUAL',
+ nextStepIds: [iteratorId],
+ },
+ steps: [
+ {
+ universalIdentifier: iteratorId,
+ name: 'Loop',
+ type: 'ITERATOR',
+ input: { items: ['one', 'two'], initialLoopStepIds: [delayId] },
+ nextStepIds: [finishId],
+ },
+ {
+ universalIdentifier: delayId,
+ name: 'Delay',
+ type: 'DELAY',
+ input: { delayType: 'DURATION', duration: { seconds: 1 } },
+ nextStepIds: [iteratorId],
+ },
+ {
+ universalIdentifier: finishId,
+ name: 'Finish',
+ type: 'EMPTY',
+ input: {},
+ nextStepIds: [],
+ },
+ ],
+ },
+};
+
+const getStep = (definition: WorkflowManifest, index: number) => {
+ const step = definition.version.steps[index];
+ if (!isDefined(step)) {
+ throw new Error(`Missing fixture step ${index}`);
+ }
+ return step;
+};
+
+describe('workflow manifest iterator cycles', () => {
+ it('rejects a loop body without a return edge', () => {
+ const invalid = structuredClone(workflow);
+ getStep(invalid, 1).nextStepIds = [];
+ const result = workflowManifestSchema.safeParse(invalid);
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error.message).toContain('must return to iterator');
+ }
+ });
+
+ it('requires nested iterators to return to their enclosing iterator after completion', () => {
+ const nested = structuredClone(workflow);
+ const innerId = '77777777-7777-4777-8777-777777777777';
+ const outer = getStep(nested, 0);
+ if (outer.type !== 'ITERATOR') {
+ throw new Error('Expected iterator');
+ }
+ outer.input.initialLoopStepIds = [innerId];
+ getStep(nested, 1).nextStepIds = [innerId];
+ nested.version.steps.push({
+ universalIdentifier: innerId,
+ name: 'Inner loop',
+ type: 'ITERATOR',
+ input: { items: ['inner'], initialLoopStepIds: [delayId] },
+ nextStepIds: [],
+ });
+ expect(workflowManifestSchema.safeParse(nested).success).toBe(false);
+ getStep(nested, 3).nextStepIds = [iteratorId];
+ expect(workflowManifestSchema.safeParse(nested).success).toBe(true);
+ });
+
+ it('rejects references to a missing step', () => {
+ const invalid = structuredClone(workflow);
+ const iterator = getStep(invalid, 0);
+ if (iterator.type !== 'ITERATOR') {
+ throw new Error('Expected iterator');
+ }
+ iterator.input.items = '{{missing.items}}';
+ expect(workflowManifestSchema.safeParse(invalid).success).toBe(false);
+ });
+
+ it('accepts a loop body returning to its iterator', () => {
+ expect(workflowManifestSchema.safeParse(workflow).success).toBe(true);
+ });
+
+ it('rejects ordinary cycles inside a loop body', () => {
+ const invalid = structuredClone(workflow);
+ getStep(invalid, 1).nextStepIds = [delayId];
+ expect(workflowManifestSchema.safeParse(invalid).success).toBe(false);
+ });
+
+ it('rejects returning to an iterator from its completed branch', () => {
+ const invalid = structuredClone(workflow);
+ getStep(invalid, 2).nextStepIds = [iteratorId];
+ expect(workflowManifestSchema.safeParse(invalid).success).toBe(false);
+ });
+
+ it('rejects an iterator pointing to itself as its loop body', () => {
+ const invalid = structuredClone(workflow);
+ const iterator = getStep(invalid, 0);
+ if (iterator.type !== 'ITERATOR') {
+ throw new Error('Expected iterator');
+ }
+ iterator.input.initialLoopStepIds = [iteratorId, delayId];
+ expect(workflowManifestSchema.safeParse(invalid).success).toBe(false);
+ });
+});
diff --git a/packages/twenty-shared/src/application/deterministic-identifier/__tests__/get-workflow-version-universal-identifier.util.spec.ts b/packages/twenty-shared/src/application/deterministic-identifier/__tests__/get-workflow-version-universal-identifier.util.spec.ts
new file mode 100644
index 00000000000..91bb5e07ec8
--- /dev/null
+++ b/packages/twenty-shared/src/application/deterministic-identifier/__tests__/get-workflow-version-universal-identifier.util.spec.ts
@@ -0,0 +1,23 @@
+import { getWorkflowVersionUniversalIdentifier } from '@/application/deterministic-identifier/get-workflow-version-universal-identifier.util';
+
+const APP = '11111111-1111-4111-8111-111111111111';
+
+describe('getWorkflowVersionUniversalIdentifier', () => {
+ it('derives a deterministic id from the workflow within its application', () => {
+ expect(
+ getWorkflowVersionUniversalIdentifier({
+ applicationUniversalIdentifier: APP,
+ workflowUniversalIdentifier: '22222222-2222-4222-8222-222222222222',
+ }),
+ ).toBe('3cafec04-e2a4-54cd-8775-601e84c13ceb');
+ });
+
+ it('gives each workflow its own version identifier', () => {
+ expect(
+ getWorkflowVersionUniversalIdentifier({
+ applicationUniversalIdentifier: APP,
+ workflowUniversalIdentifier: '33333333-3333-4333-8333-333333333333',
+ }),
+ ).toBe('918dd6c5-f3a0-5dd8-9944-7b70ed903d87');
+ });
+});
diff --git a/packages/twenty-shared/src/application/deterministic-identifier/get-workflow-version-universal-identifier.util.ts b/packages/twenty-shared/src/application/deterministic-identifier/get-workflow-version-universal-identifier.util.ts
new file mode 100644
index 00000000000..875e001fb48
--- /dev/null
+++ b/packages/twenty-shared/src/application/deterministic-identifier/get-workflow-version-universal-identifier.util.ts
@@ -0,0 +1,15 @@
+import { computeDeterministicUuid } from '@/application/deterministic-identifier/compute-deterministic-uuid.util';
+
+export const getWorkflowVersionUniversalIdentifier = ({
+ applicationUniversalIdentifier,
+ workflowUniversalIdentifier,
+}: {
+ applicationUniversalIdentifier: string;
+ workflowUniversalIdentifier: string;
+}): string => {
+ return computeDeterministicUuid({
+ entityNamespace: 'workflowVersion',
+ value: workflowUniversalIdentifier,
+ applicationUniversalIdentifier,
+ });
+};
diff --git a/packages/twenty-shared/src/application/index.ts b/packages/twenty-shared/src/application/index.ts
index a4e3555417b..d6969d29e6f 100644
--- a/packages/twenty-shared/src/application/index.ts
+++ b/packages/twenty-shared/src/application/index.ts
@@ -133,6 +133,7 @@ export { getViewFilterUniversalIdentifier } from './deterministic-identifier/get
export { getViewGroupUniversalIdentifier } from './deterministic-identifier/get-view-group-universal-identifier.util';
export { getViewSortUniversalIdentifier } from './deterministic-identifier/get-view-sort-universal-identifier.util';
export { getViewUniversalIdentifier } from './deterministic-identifier/get-view-universal-identifier.util';
+export { getWorkflowVersionUniversalIdentifier } from './deterministic-identifier/get-workflow-version-universal-identifier.util';
export type {
EnqueueJobOptions,
EnqueueJobInput,
@@ -259,3 +260,7 @@ export type {
ViewManifest,
} from './viewManifestType';
export type { WorkflowActionTriggerSettings } from './workflowActionTriggerSettingsType';
+export type { WorkflowManifest } from './workflowManifestType';
+export { workflowManifestSchema } from './workflowManifestType';
+export type { WorkflowStepManifest } from './workflowStepManifestType';
+export { workflowStepManifestSchema } from './workflowStepManifestType';
diff --git a/packages/twenty-shared/src/application/manifestType.ts b/packages/twenty-shared/src/application/manifestType.ts
index f77f56156a8..440d758de70 100644
--- a/packages/twenty-shared/src/application/manifestType.ts
+++ b/packages/twenty-shared/src/application/manifestType.ts
@@ -1,3 +1,4 @@
+import { type WorkflowManifest } from './workflowManifestType';
import { type AppLocale } from '@/translations';
import { type AgentManifest } from './agentManifestType';
@@ -33,6 +34,7 @@ export type TranslationsManifest = Partial<
>;
export type Manifest = {
+ workflows?: WorkflowManifest[];
application: ApplicationManifest;
objects: ObjectManifest[];
fields: FieldManifest[];
diff --git a/packages/twenty-shared/src/application/workflowManifestType.ts b/packages/twenty-shared/src/application/workflowManifestType.ts
new file mode 100644
index 00000000000..0a0fa55ab7e
--- /dev/null
+++ b/packages/twenty-shared/src/application/workflowManifestType.ts
@@ -0,0 +1,71 @@
+import { z } from 'zod';
+
+import { validateWorkflowVariableReferences } from '@/workflow/validation/utils/validate-workflow-variable-references.util';
+
+import { workflowStepManifestSchema } from '@/application/workflowStepManifestType';
+import { buildWorkflowGraph } from '@/workflow/validation/utils/build-workflow-graph.util';
+import { validateWorkflowExecutionPaths } from '@/workflow/validation/utils/validate-workflow-execution-paths.util';
+import { validateWorkflowGraph } from '@/workflow/validation/utils/validate-workflow-graph.util';
+
+export const workflowManifestSchema = z
+ .strictObject({
+ universalIdentifier: z.uuid(),
+ name: z.string().min(1),
+ version: z.strictObject({
+ trigger: z.strictObject({
+ universalIdentifier: z.uuid(),
+ type: z.literal('MANUAL'),
+ nextStepIds: z.array(z.uuid()).min(1),
+ }),
+ steps: z.array(workflowStepManifestSchema).min(1),
+ }),
+ })
+ .superRefine((workflow, context) => {
+ const { steps, trigger } = workflow.version;
+ const identities = [
+ workflow.universalIdentifier,
+ trigger.universalIdentifier,
+ ...steps.map((step) => step.universalIdentifier),
+ ];
+
+ if (new Set(identities).size !== identities.length) {
+ context.addIssue({
+ code: 'custom',
+ message:
+ 'Workflow, trigger and steps must have distinct universal identifiers',
+ });
+ }
+
+ const validatableWorkflow = {
+ trigger,
+ steps: steps.map((step) => ({
+ ...step,
+ id: step.universalIdentifier,
+ settings: { input: step.input },
+ })),
+ };
+ const graph = buildWorkflowGraph(validatableWorkflow);
+ for (const issue of [
+ ...validateWorkflowGraph({
+ workflow: validatableWorkflow,
+ graph,
+ }),
+ ...validateWorkflowExecutionPaths({
+ workflow: validatableWorkflow,
+ graph,
+ }),
+ ...validateWorkflowVariableReferences({
+ workflow: validatableWorkflow,
+ graph,
+ stepsById: new Map(
+ validatableWorkflow.steps.map((step) => [step.id, step]),
+ ),
+ }),
+ ]) {
+ if (issue.severity === 'error') {
+ context.addIssue({ code: 'custom', message: issue.message });
+ }
+ }
+ });
+
+export type WorkflowManifest = z.input<typeof workflowManifestSchema>;
diff --git a/packages/twenty-shared/src/application/workflowStepManifestType.ts b/packages/twenty-shared/src/application/workflowStepManifestType.ts
new file mode 100644
index 00000000000..30dae3e8b5d
--- /dev/null
+++ b/packages/twenty-shared/src/application/workflowStepManifestType.ts
@@ -0,0 +1,199 @@
+import { z } from 'zod';
+
+import { isDefined } from '@/utils/validation/isDefined';
+
+import { workflowSendEmailActionSettingsSchema } from '@/workflow/schemas/send-email-action-settings-schema';
+import { workflowCreateCalendarEventActionSettingsSchema } from '@/workflow/schemas/create-calendar-event-action-settings-schema';
+import { workflowHttpRequestActionSettingsSchema } from '@/workflow/schemas/http-request-action-settings-schema';
+import { workflowClassifyActionSettingsSchema } from '@/workflow/schemas/classify-action-settings-schema';
+import { workflowIteratorActionSettingsSchema } from '@/workflow/schemas/iterator-action-settings-schema';
+import { workflowDelayActionSettingsSchema } from '@/workflow/schemas/workflow-delay-action-settings-schema';
+import { workflowEmptyActionSettingsSchema } from '@/workflow/schemas/empty-action-settings-schema';
+import { baseWorkflowActionSettingsSchema } from '@/workflow/schemas/base-workflow-action-settings-schema';
+import { workflowCreateRecordActionSettingsSchema } from '@/workflow/schemas/create-record-action-settings-schema';
+import { workflowUpdateRecordActionSettingsSchema } from '@/workflow/schemas/update-record-action-settings-schema';
+import { workflowUpsertRecordActionSettingsSchema } from '@/workflow/schemas/upsert-record-action-settings-schema';
+import { workflowDeleteRecordActionSettingsSchema } from '@/workflow/schemas/delete-record-action-settings-schema';
+import { workflowFindRecordsActionSettingsSchema } from '@/workflow/schemas/find-records-action-settings-schema';
+import { workflowFormActionSettingsSchema } from '@/workflow/schemas/form-action-settings-schema';
+import { workflowFilterActionSettingsSchema } from '@/workflow/schemas/filter-action-settings-schema';
+import { workflowIfElseActionSettingsSchema } from '@/workflow/schemas/if-else-action-settings-schema';
+import { stepFilterSchema } from '@/workflow/schemas/step-filter-schema';
+import { workflowPickRecordStrategySchema } from '@/workflow/schemas/pick-record-action-settings-schema';
+
+const baseStepShape = {
+ universalIdentifier: z.uuid(),
+ name: z.string().min(1),
+ nextStepIds: z.array(z.uuid()),
+ position: z.object({ x: z.number(), y: z.number() }).optional(),
+ outputSchema: z.record(z.string(), z.unknown()).optional(),
+ expectedOutputSchema: z.record(z.string(), z.unknown()).optional(),
+ errorHandlingOptions:
+ baseWorkflowActionSettingsSchema.shape.errorHandlingOptions.optional(),
+};
+
+const stepSchema = <TType extends string, TInput extends z.ZodType>(
+ type: TType,
+ input: TInput,
+) => z.strictObject({ ...baseStepShape, type: z.literal(type), input });
+
+const fieldReferenceSchema = z.looseObject({
+ fieldMetadataUniversalIdentifier: z.uuid(),
+ fieldMetadataId: z.never().optional(),
+});
+
+const stepFilterManifestSchema = stepFilterSchema
+ .omit({ fieldMetadataId: true })
+ .extend({ fieldMetadataUniversalIdentifier: z.uuid().optional() })
+ .strict();
+
+const recordObjectShape = { objectUniversalIdentifier: z.uuid() };
+
+export const workflowStepManifestSchema = z.discriminatedUnion('type', [
+ z.strictObject({
+ ...baseStepShape,
+ type: z.literal('LOGIC_FUNCTION'),
+ logicFunctionUniversalIdentifier: z.uuid(),
+ input: z.record(z.string(), z.unknown()),
+ }),
+ stepSchema('SEND_EMAIL', workflowSendEmailActionSettingsSchema.shape.input),
+ stepSchema(
+ 'CREATE_CALENDAR_EVENT',
+ workflowCreateCalendarEventActionSettingsSchema.shape.input,
+ ),
+ stepSchema(
+ 'HTTP_REQUEST',
+ workflowHttpRequestActionSettingsSchema.shape.input,
+ ),
+ stepSchema('CLASSIFY', workflowClassifyActionSettingsSchema.shape.input),
+ stepSchema('ITERATOR', workflowIteratorActionSettingsSchema.shape.input),
+ stepSchema('DELAY', workflowDelayActionSettingsSchema.shape.input),
+ stepSchema('EMPTY', workflowEmptyActionSettingsSchema.shape.input),
+ stepSchema('DRAFT_EMAIL', workflowSendEmailActionSettingsSchema.shape.input),
+ stepSchema(
+ 'CREATE_RECORD',
+ workflowCreateRecordActionSettingsSchema.shape.input
+ .omit({ objectName: true })
+ .extend(recordObjectShape)
+ .strict(),
+ ),
+ stepSchema(
+ 'UPDATE_RECORD',
+ workflowUpdateRecordActionSettingsSchema.shape.input
+ .omit({ objectName: true })
+ .extend(recordObjectShape)
+ .strict(),
+ ),
+ stepSchema(
+ 'UPSERT_RECORD',
+ workflowUpsertRecordActionSettingsSchema.shape.input
+ .omit({ objectName: true })
+ .extend(recordObjectShape)
+ .strict(),
+ ),
+ stepSchema(
+ 'DELETE_RECORD',
+ workflowDeleteRecordActionSettingsSchema.shape.input
+ .omit({ objectName: true })
+ .extend(recordObjectShape)
+ .strict(),
+ ),
+ stepSchema(
+ 'FIND_RECORDS',
+ workflowFindRecordsActionSettingsSchema.shape.input
+ .omit({ objectName: true, filter: true, orderBy: true })
+ .extend({
+ ...recordObjectShape,
+ filter: z
+ .strictObject({
+ recordFilterGroups: z
+ .array(z.record(z.string(), z.unknown()))
+ .optional(),
+ recordFilters: z.array(fieldReferenceSchema).optional(),
+ })
+ .optional(),
+ orderBy: z
+ .strictObject({
+ recordSorts: z
+ .array(
+ fieldReferenceSchema.extend({
+ direction: z.enum(['ASC', 'DESC']),
+ subFieldName: z.string().nullable().optional(),
+ }),
+ )
+ .optional(),
+ })
+ .optional(),
+ })
+ .strict(),
+ ),
+ stepSchema(
+ 'PICK_RECORD',
+ z
+ .strictObject({
+ ...recordObjectShape,
+ strategy: workflowPickRecordStrategySchema,
+ recordIds: z.array(z.string()),
+ loadBalance: z
+ .strictObject({
+ objectUniversalIdentifier: z.uuid(),
+ fieldUniversalIdentifier: z.uuid(),
+ })
+ .optional(),
+ })
+ .superRefine((input, context) => {
+ if (
+ input.strategy === 'LOAD_BALANCED' &&
+ !isDefined(input.loadBalance)
+ ) {
+ context.addIssue({
+ code: 'custom',
+ path: ['loadBalance'],
+ message: 'loadBalance is required when strategy is LOAD_BALANCED',
+ });
+ }
+ }),
+ ),
+ stepSchema(
+ 'FILTER',
+ workflowFilterActionSettingsSchema.shape.input.extend({
+ stepFilters: z.array(stepFilterManifestSchema),
+ }),
+ ),
+ stepSchema(
+ 'IF_ELSE',
+ workflowIfElseActionSettingsSchema.shape.input.extend({
+ stepFilters: z.array(stepFilterManifestSchema),
+ }),
+ ),
+ stepSchema(
+ 'FORM',
+ z.array(
+ workflowFormActionSettingsSchema.shape.input.element
+ .extend({ settings: z.record(z.string(), z.unknown()).optional() })
+ .superRefine((field, context) => {
+ if (
+ field.type === 'RECORD' &&
+ !z.uuid().safeParse(field.settings?.objectUniversalIdentifier)
+ .success
+ ) {
+ context.addIssue({
+ code: 'custom',
+ path: ['settings', 'objectUniversalIdentifier'],
+ message:
+ 'Record picker fields require an object universal identifier',
+ });
+ }
+ }),
+ ),
+ ),
+ stepSchema(
+ 'AI_AGENT',
+ z.strictObject({
+ agentUniversalIdentifier: z.uuid().optional(),
+ prompt: z.string(),
+ }),
+ ),
+]);
+
+export type WorkflowStepManifest = z.infer<typeof workflowStepManifestSchema>;
diff --git a/packages/twenty-shared/src/types/FeatureFlagKey.ts b/packages/twenty-shared/src/types/FeatureFlagKey.ts
index 40fbabb184b..4b93bb1856c 100644
--- a/packages/twenty-shared/src/types/FeatureFlagKey.ts
+++ b/packages/twenty-shared/src/types/FeatureFlagKey.ts
@@ -1,4 +1,5 @@
export enum FeatureFlagKey {
+ IS_APPLICATION_WORKFLOWS_ENABLED = 'IS_APPLICATION_WORKFLOWS_ENABLED',
IS_ASYNC_CSV_EXPORT_ENABLED = 'IS_ASYNC_CSV_EXPORT_ENABLED',
IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED = 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED',
IS_JSON_FILTER_ENABLED = 'IS_JSON_FILTER_ENABLED',
diff --git a/packages/twenty-shared/src/utils/index.ts b/packages/twenty-shared/src/utils/index.ts
index e53071b9b24..d08317932e7 100644
--- a/packages/twenty-shared/src/utils/index.ts
+++ b/packages/twenty-shared/src/utils/index.ts
@@ -219,6 +219,12 @@ export { resolveRichTextVariables } from './rich-text-variable-resolver';
export { safeParseRelativeDateFilterJsonStringified } from './safeParseRelativeDateFilterJsonStringified';
export { getGenericOperationName } from './sentry/getGenericOperationName';
export { getHumanReadableNameFromCode } from './sentry/getHumanReadableNameFromCode';
+export { getEnabledAddressSubFields } from './sort/getEnabledAddressSubFields';
+export type { OrderByFieldMetadata } from './sort/getOrderByForFieldMetadataType';
+export { getOrderByForFieldMetadataType } from './sort/getOrderByForFieldMetadataType';
+export { getOrderByForRelationField } from './sort/getOrderByForRelationField';
+export { resolveAddressSortSubField } from './sort/resolveAddressSortSubField';
+export { resolvePrimaryFullNameSortSubField } from './sort/resolvePrimaryFullNameSortSubField';
export { appendCopySuffix } from './strings/appendCopySuffix';
export { camelToKebab } from './strings/camelToKebab';
export { camelToSnakeCase } from './strings/camelToSnakeCase';
diff --git a/packages/twenty-front/src/modules/object-metadata/utils/__tests__/getOrderByForFieldMetadataType.test.ts b/packages/twenty-shared/src/utils/sort/__tests__/getOrderByForFieldMetadataType.test.ts
similarity index 82%
rename from packages/twenty-front/src/modules/object-metadata/utils/__tests__/getOrderByForFieldMetadataType.test.ts
rename to packages/twenty-shared/src/utils/sort/__tests__/getOrderByForFieldMetadataType.test.ts
index 19b3da12198..aa31a2971a1 100644
--- a/packages/twenty-front/src/modules/object-metadata/utils/__tests__/getOrderByForFieldMetadataType.test.ts
+++ b/packages/twenty-shared/src/utils/sort/__tests__/getOrderByForFieldMetadataType.test.ts
@@ -1,12 +1,13 @@
-import { type FieldMetadataItem } from '@/object-metadata/types/FieldMetadataItem';
-import { getOrderByForFieldMetadataType } from '@/object-metadata/utils/getOrderByForFieldMetadataType';
-import { FieldMetadataType } from '~/generated-metadata/graphql';
+import {
+ getOrderByForFieldMetadataType,
+ type OrderByFieldMetadata,
+} from '@/utils/sort/getOrderByForFieldMetadataType';
+import { FieldMetadataType } from '@/types';
const buildField = (
- overrides: Pick<FieldMetadataItem, 'type' | 'name'> &
- Partial<Pick<FieldMetadataItem, 'id' | 'settings'>>,
-): Pick<FieldMetadataItem, 'id' | 'name' | 'type' | 'settings'> => ({
- id: 'field-id',
+ overrides: Pick<OrderByFieldMetadata, 'type' | 'name'> &
+ Partial<Pick<OrderByFieldMetadata, 'settings'>>,
+): OrderByFieldMetadata => ({
...overrides,
});
diff --git a/packages/twenty-front/src/modules/object-metadata/utils/__tests__/resolveAddressSortSubField.test.ts b/packages/twenty-shared/src/utils/sort/__tests__/resolveAddressSortSubField.test.ts
similarity index 94%
rename from packages/twenty-front/src/modules/object-metadata/utils/__tests__/resolveAddressSortSubField.test.ts
rename to packages/twenty-shared/src/utils/sort/__tests__/resolveAddressSortSubField.test.ts
index 3a3d8c9b251..3c1cb7367a4 100644
--- a/packages/twenty-front/src/modules/object-metadata/utils/__tests__/resolveAddressSortSubField.test.ts
+++ b/packages/twenty-shared/src/utils/sort/__tests__/resolveAddressSortSubField.test.ts
@@ -1,4 +1,4 @@
-import { resolveAddressSortSubField } from '@/object-metadata/utils/resolveAddressSortSubField';
+import { resolveAddressSortSubField } from '@/utils/sort/resolveAddressSortSubField';
describe('resolveAddressSortSubField', () => {
it('returns the requested sub-field when it is enabled', () => {
diff --git a/packages/twenty-front/src/modules/object-metadata/utils/__tests__/resolvePrimaryFullNameSortSubField.test.ts b/packages/twenty-shared/src/utils/sort/__tests__/resolvePrimaryFullNameSortSubField.test.ts
similarity index 90%
rename from packages/twenty-front/src/modules/object-metadata/utils/__tests__/resolvePrimaryFullNameSortSubField.test.ts
rename to packages/twenty-shared/src/utils/sort/__tests__/resolvePrimaryFullNameSortSubField.test.ts
index 2eff18c4fd5..e469c4afbcd 100644
--- a/packages/twenty-front/src/modules/object-metadata/utils/__tests__/resolvePrimaryFullNameSortSubField.test.ts
+++ b/packages/twenty-shared/src/utils/sort/__tests__/resolvePrimaryFullNameSortSubField.test.ts
@@ -1,4 +1,4 @@
-import { resolvePrimaryFullNameSortSubField } from '@/object-metadata/utils/resolvePrimaryFullNameSortSubField';
+import { resolvePrimaryFullNameSortSubField } from '@/utils/sort/resolvePrimaryFullNameSortSubField';
describe('resolvePrimaryFullNameSortSubField', () => {
it('returns the requested sub-field when it is a recognized full-name sub-field', () => {
diff --git a/packages/twenty-shared/src/utils/sort/getEnabledAddressSubFields.ts b/packages/twenty-shared/src/utils/sort/getEnabledAddressSubFields.ts
new file mode 100644
index 00000000000..012ea261f30
--- /dev/null
+++ b/packages/twenty-shared/src/utils/sort/getEnabledAddressSubFields.ts
@@ -0,0 +1,19 @@
+import { DEFAULT_VISIBLE_ADDRESS_SUBFIELDS } from '@/constants';
+import {
+ type AllowedAddressSubField,
+ type FieldMetadataSettingsMapping,
+ type FieldMetadataType,
+} from '@/types';
+import { isNonEmptyArray } from '@/utils';
+
+export const getEnabledAddressSubFields = (
+ settings:
+ | FieldMetadataSettingsMapping[FieldMetadataType.ADDRESS]
+ | null
+ | undefined,
+): readonly AllowedAddressSubField[] => {
+ if (isNonEmptyArray(settings?.subFields)) {
+ return settings.subFields;
+ }
+ return DEFAULT_VISIBLE_ADDRESS_SUBFIELDS;
+};
diff --git a/packages/twenty-shared/src/utils/sort/getOrderByForFieldMetadataType.ts b/packages/twenty-shared/src/utils/sort/getOrderByForFieldMetadataType.ts
new file mode 100644
index 00000000000..61fe18af9d6
--- /dev/null
+++ b/packages/twenty-shared/src/utils/sort/getOrderByForFieldMetadataType.ts
@@ -0,0 +1,101 @@
+import {
+ type FieldMetadataSettingsMapping,
+ FieldMetadataType,
+ type OrderBy,
+ type RecordGqlOperationOrderBy,
+} from '@/types';
+import { resolveAddressSortSubField } from '@/utils/sort/resolveAddressSortSubField';
+import { resolvePrimaryFullNameSortSubField } from '@/utils/sort/resolvePrimaryFullNameSortSubField';
+
+export type OrderByFieldMetadata = {
+ name: string;
+ type: `${FieldMetadataType}`;
+ settings?: unknown;
+};
+
+export const getOrderByForFieldMetadataType = ({
+ field,
+ orderByDirection,
+ primaryCompositeSubField,
+}: {
+ field: OrderByFieldMetadata;
+ orderByDirection: OrderBy | null | undefined;
+ primaryCompositeSubField?: string | null;
+}): RecordGqlOperationOrderBy => {
+ switch (field.type) {
+ case FieldMetadataType.FULL_NAME: {
+ const primarySubField = resolvePrimaryFullNameSortSubField({
+ requestedPrimarySubField: primaryCompositeSubField,
+ });
+ const secondarySubField =
+ primarySubField === 'firstName' ? 'lastName' : 'firstName';
+ const direction = orderByDirection ?? 'AscNullsLast';
+ return [
+ { [field.name]: { [primarySubField]: direction } },
+ { [field.name]: { [secondarySubField]: direction } },
+ ];
+ }
+ case FieldMetadataType.ADDRESS: {
+ const subField = resolveAddressSortSubField({
+ settings: field.settings as
+ | FieldMetadataSettingsMapping[FieldMetadataType.ADDRESS]
+ | null
+ | undefined,
+ primaryCompositeSubField,
+ });
+ return [
+ {
+ [field.name]: {
+ [subField]: orderByDirection ?? 'AscNullsLast',
+ },
+ },
+ ];
+ }
+ case FieldMetadataType.CURRENCY:
+ return [
+ {
+ [field.name]: {
+ amountMicros: orderByDirection ?? 'AscNullsLast',
+ },
+ },
+ ];
+ case FieldMetadataType.ACTOR:
+ return [
+ {
+ [field.name]: {
+ name: orderByDirection ?? 'AscNullsLast',
+ },
+ },
+ ];
+ case FieldMetadataType.LINKS:
+ return [
+ {
+ [field.name]: {
+ primaryLinkUrl: orderByDirection ?? 'AscNullsLast',
+ },
+ },
+ ];
+ case FieldMetadataType.EMAILS:
+ return [
+ {
+ [field.name]: {
+ primaryEmail: orderByDirection ?? 'AscNullsLast',
+ },
+ },
+ ];
+ case FieldMetadataType.PHONES:
+ return [
+ {
+ [field.name]: {
+ primaryPhoneNumber: orderByDirection ?? 'AscNullsLast',
+ },
+ },
+ ];
+ default:
+ return [
+ {
+ [field.name]: orderByDirection ?? 'AscNullsLast',
+ },
+ ];
+ }
+};
diff --git a/packages/twenty-shared/src/utils/sort/getOrderByForRelationField.ts b/packages/twenty-shared/src/utils/sort/getOrderByForRelationField.ts
new file mode 100644
index 00000000000..a19ee5aa12c
--- /dev/null
+++ b/packages/twenty-shared/src/utils/sort/getOrderByForRelationField.ts
@@ -0,0 +1,26 @@
+import { type OrderBy, type RecordGqlOperationOrderBy } from '@/types';
+import {
+ getOrderByForFieldMetadataType,
+ type OrderByFieldMetadata,
+} from '@/utils/sort/getOrderByForFieldMetadataType';
+import { isDefined } from '@/utils/validation/isDefined';
+
+export const getOrderByForRelationField = ({
+ field,
+ labelIdentifierField,
+ orderByDirection,
+}: {
+ field: { name: string };
+ labelIdentifierField: OrderByFieldMetadata | undefined;
+ orderByDirection: OrderBy;
+}): RecordGqlOperationOrderBy => {
+ if (!isDefined(labelIdentifierField)) {
+ return [{ [`${field.name}Id`]: orderByDirection }];
+ }
+ return getOrderByForFieldMetadataType({
+ field: labelIdentifierField,
+ orderByDirection,
+ }).map((entry) => {
+ return { [field.name]: entry };
+ });
+};
diff --git a/packages/twenty-shared/src/utils/sort/resolveAddressSortSubField.ts b/packages/twenty-shared/src/utils/sort/resolveAddressSortSubField.ts
new file mode 100644
index 00000000000..8e2e91844e9
--- /dev/null
+++ b/packages/twenty-shared/src/utils/sort/resolveAddressSortSubField.ts
@@ -0,0 +1,42 @@
+import { getEnabledAddressSubFields } from '@/utils/sort/getEnabledAddressSubFields';
+import {
+ ALLOWED_ADDRESS_SUBFIELDS,
+ type AllowedAddressSubField,
+ type FieldMetadataSettingsMapping,
+ type FieldMetadataType,
+} from '@/types';
+import { isDefined } from '@/utils';
+
+const DEFAULT_SUB_FIELD: AllowedAddressSubField = 'addressCity';
+
+const isAllowedAddressSubField = (
+ value: string | null | undefined,
+): value is AllowedAddressSubField =>
+ ALLOWED_ADDRESS_SUBFIELDS.includes(value as AllowedAddressSubField);
+
+export const resolveAddressSortSubField = ({
+ settings,
+ primaryCompositeSubField,
+}: {
+ settings:
+ | FieldMetadataSettingsMapping[FieldMetadataType.ADDRESS]
+ | null
+ | undefined;
+ primaryCompositeSubField?: string | null;
+}): AllowedAddressSubField => {
+ const enabledSubFields = getEnabledAddressSubFields(settings);
+
+ if (
+ isDefined(primaryCompositeSubField) &&
+ isAllowedAddressSubField(primaryCompositeSubField) &&
+ enabledSubFields.includes(primaryCompositeSubField)
+ ) {
+ return primaryCompositeSubField;
+ }
+
+ if (enabledSubFields.includes(DEFAULT_SUB_FIELD)) {
+ return DEFAULT_SUB_FIELD;
+ }
+
+ return enabledSubFields[0] ?? DEFAULT_SUB_FIELD;
+};
diff --git a/packages/twenty-shared/src/utils/sort/resolvePrimaryFullNameSortSubField.ts b/packages/twenty-shared/src/utils/sort/resolvePrimaryFullNameSortSubField.ts
new file mode 100644
index 00000000000..cbfd868f66d
--- /dev/null
+++ b/packages/twenty-shared/src/utils/sort/resolvePrimaryFullNameSortSubField.ts
@@ -0,0 +1,26 @@
+import { ALLOWED_FULL_NAME_SORT_SUBFIELDS } from '@/constants';
+import { type AllowedFullNameSortSubField } from '@/types';
+import { isDefined } from '@/utils';
+
+const DEFAULT_PRIMARY_SUB_FIELD: AllowedFullNameSortSubField = 'firstName';
+
+const isAllowedFullNameSortSubField = (
+ value: string | null | undefined,
+): value is AllowedFullNameSortSubField =>
+ ALLOWED_FULL_NAME_SORT_SUBFIELDS.includes(
+ value as AllowedFullNameSortSubField,
+ );
+
+export const resolvePrimaryFullNameSortSubField = ({
+ requestedPrimarySubField,
+}: {
+ requestedPrimarySubField?: string | null;
+} = {}): AllowedFullNameSortSubField => {
+ if (
+ isDefined(requestedPrimarySubField) &&
+ isAllowedFullNameSortSubField(requestedPrimarySubField)
+ ) {
+ return requestedPrimarySubField;
+ }
+ return DEFAULT_PRIMARY_SUB_FIELD;
+};
diff --git a/packages/twenty-shared/src/workflow/index.ts b/packages/twenty-shared/src/workflow/index.ts
index 0c985fd8f02..9003c0169f2 100644
--- a/packages/twenty-shared/src/workflow/index.ts
+++ b/packages/twenty-shared/src/workflow/index.ts
@@ -178,6 +178,7 @@ export {
getStepOutgoingStepIds,
} from './validation/utils/get-step-outgoing-step-ids.util';
export { getVariablePathSuggestions } from './validation/utils/get-variable-path-suggestions.util';
+export { validateWorkflowExecutionPaths } from './validation/utils/validate-workflow-execution-paths.util';
export { validateWorkflowGraph } from './validation/utils/validate-workflow-graph.util';
export { validateWorkflowStepParams } from './validation/utils/validate-workflow-step-params.util';
export { validateWorkflowVariableReferences } from './validation/utils/validate-workflow-variable-references.util';
diff --git a/packages/twenty-shared/src/workflow/validation/types/WorkflowValidation.ts b/packages/twenty-shared/src/workflow/validation/types/WorkflowValidation.ts
index 7e0057968d4..de5a77bb7b4 100644
--- a/packages/twenty-shared/src/workflow/validation/types/WorkflowValidation.ts
+++ b/packages/twenty-shared/src/workflow/validation/types/WorkflowValidation.ts
@@ -27,6 +27,8 @@ export type WorkflowValidationIssueCode =
| 'IF_ELSE_INSUFFICIENT_BRANCHES'
| 'IF_ELSE_BRANCH_HAS_NO_NEXT_STEP'
| 'ITERATOR_MISSING_LOOP_BODY'
+ | 'WORKFLOW_CYCLE'
+ | 'ITERATOR_MISSING_RETURN'
| 'VARIABLE_INVALID_PATH'
| 'VARIABLE_UNKNOWN_STEP'
| 'VARIABLE_NOT_UPSTREAM'
diff --git a/packages/twenty-shared/src/workflow/validation/utils/validate-workflow-execution-paths.util.ts b/packages/twenty-shared/src/workflow/validation/utils/validate-workflow-execution-paths.util.ts
new file mode 100644
index 00000000000..1f47d0e7b10
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/validation/utils/validate-workflow-execution-paths.util.ts
@@ -0,0 +1,70 @@
+import { isDefined } from '@/utils/validation/isDefined';
+import { WorkflowActionType } from '@/workflow/types/WorkflowActionType';
+import { isIteratorStepInput } from '@/workflow/validation/guards/isIteratorStepInput';
+import {
+ type ValidatableWorkflow,
+ type WorkflowValidationIssue,
+} from '@/workflow/validation/types/WorkflowValidation';
+import { type WorkflowGraph } from '@/workflow/validation/utils/build-workflow-graph.util';
+
+export const validateWorkflowExecutionPaths = ({
+ workflow,
+ graph,
+}: {
+ workflow: ValidatableWorkflow;
+ graph: WorkflowGraph;
+}): WorkflowValidationIssue[] => {
+ const issues: WorkflowValidationIssue[] = [];
+ const visiting = new Set<string>();
+ const visited = new Set<string>();
+ const stepsById = new Map(
+ (workflow.steps ?? []).map((step) => [step.id, step]),
+ );
+ const visit = (
+ id: string,
+ enclosingIterators: string[] = [],
+ sourceId?: string,
+ ): void => {
+ const enclosingIterator = enclosingIterators[enclosingIterators.length - 1];
+ if (visiting.has(id)) {
+ if (id !== sourceId && enclosingIterator === id) {
+ return;
+ }
+ issues.push({
+ severity: 'error',
+ code: 'WORKFLOW_CYCLE',
+ stepId: id,
+ message: `Workflow contains a cycle at step ${id}`,
+ });
+ return;
+ }
+ const step = stepsById.get(id);
+ const visitKey = `${id}:${enclosingIterators.join(',')}`;
+ if (!isDefined(step) || visited.has(visitKey)) {
+ return;
+ }
+ visiting.add(id);
+ if (isIteratorStepInput(step)) {
+ (step.settings.input.initialLoopStepIds ?? []).forEach((nextId) =>
+ visit(nextId, [...enclosingIterators, id], id),
+ );
+ }
+ const destinations =
+ step.type === WorkflowActionType.ITERATOR
+ ? (step.nextStepIds ?? [])
+ : (graph.childrenByStepId.get(id) ?? []);
+ if (isDefined(enclosingIterator) && destinations.length === 0) {
+ issues.push({
+ severity: 'error',
+ code: 'ITERATOR_MISSING_RETURN',
+ stepId: id,
+ message: `Loop body step ${id} must return to iterator ${enclosingIterator}`,
+ });
+ }
+ destinations.forEach((nextId) => visit(nextId, enclosingIterators, id));
+ visiting.delete(id);
+ visited.add(visitKey);
+ };
+ workflow.trigger?.nextStepIds?.forEach((id) => visit(id));
+ return issues;
+};