The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Allow removing workflows from an application manifest (#27309)
Thomas Trompetteae39d73f4d98
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.tsindex 1b06e468b2f..e6c3dd0d658 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@@ -225,7 +225,6 @@ export class ApplicationManifestMigrationService {idByUniversalIdentifierByMetadataName,isApplicationWorkflowsEnabled:featureFlagsMap[FeatureFlagKey.IS_APPLICATION_WORKFLOWS_ENABLED],- inferDeletionFromMissingEntities,now,});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.tsindex 8947577b6f8..6d74130b082 100644--- 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@@ -52,7 +52,6 @@ describe('application workflow installation gate', () => {existingAllFlatEntityMaps: createEmptyAllFlatEntityMaps(),idByUniversalIdentifierByMetadataName: {},isApplicationWorkflowsEnabled,- inferDeletionFromMissingEntities: true,now: '2026-09-28T00:00:00.000Z',}),).toThrow('Application workflows are not enabled');@@ -63,7 +62,6 @@ describe('application workflow installation gate', () => {const compute = ({workflows = MANIFEST.workflows ?? [],fromAllFlatEntityMaps = createEmptyAllFlatEntityMaps(),- inferDeletionFromMissingEntities = true,} = {}) => {for (const workflow of Object.values(fromAllFlatEntityMaps.flatWorkflowMaps.byUniversalIdentifier,@@ -89,7 +87,6 @@ const compute = ({existingAllFlatEntityMaps: fromAllFlatEntityMaps,idByUniversalIdentifierByMetadataName: {},isApplicationWorkflowsEnabled: true,- inferDeletionFromMissingEntities,now: '2026-09-28T00:00:00.000Z',});@@ -133,20 +130,11 @@ describe('application workflow manifest updates', () => {);});- it('rejects deleting a workflow on a full sync', () => {- expect(() =>- compute({ workflows: [], fromAllFlatEntityMaps: compute() }),- ).toThrow('Removing application workflows is not supported');- });+ it('leaves an omitted workflow out of the target maps', () => {+ const before = compute();+ const after = compute({ workflows: [], fromAllFlatEntityMaps: before });- it('allows omitted workflows on additive syncs', () => {- expect(() =>- compute({- workflows: [],- fromAllFlatEntityMaps: compute(),- inferDeletionFromMissingEntities: false,- }),- ).not.toThrow();+ expect(after.flatWorkflowMaps.byUniversalIdentifier).toEqual({});});it('rejects unknown record fields and update selections in one error', () => {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.tsindex 9e1137fcdb6..c34472c6424 100644--- 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@@ -4,7 +4,6 @@ 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';@@ -26,7 +25,6 @@ export const addWorkflowManifestsToFlatEntityMapsOrThrow = ({existingAllFlatEntityMaps,idByUniversalIdentifierByMetadataName,isApplicationWorkflowsEnabled,- inferDeletionFromMissingEntities,now,}: {workflows: WorkflowManifest[];@@ -36,7 +34,6 @@ export const addWorkflowManifestsToFlatEntityMapsOrThrow = ({existingAllFlatEntityMaps: AllFlatEntityMaps;idByUniversalIdentifierByMetadataName: IdByUniversalIdentifierByMetadataName;isApplicationWorkflowsEnabled: boolean | undefined;- inferDeletionFromMissingEntities: boolean;now: string;}): void => {if (workflows.length > 0 && !isApplicationWorkflowsEnabled) {@@ -52,28 +49,6 @@ export const addWorkflowManifestsToFlatEntityMapsOrThrow = ({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,diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/application-workflow-removal.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/application-workflow-removal.integration-spec.tsnew file mode 100644index 00000000000..a9419a2a30a--- /dev/null+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/application-workflow-removal.integration-spec.ts@@ -0,0 +1,294 @@+import { randomUUID } from 'node:crypto';++import {+ buildTestApplicationManifest,+ buildTestApplicationWorkflow,+ countCoreWorkflows,+ countTestCompanies,+ countTestWorkflowRuns,+ createCompanyStep,+ findTestWorkflowRun,+ findTestWorkflowVersionId,+ formStep,+ logicFunctionStep,+ runCoreWorkflowVersion,+ type TestApplicationWorkflow,+ waitForTestWorkflowRun,+} from 'test/integration/graphql/suites/workflow/utils/application-workflow-test.util';+import { submitFormStep } from 'test/integration/graphql/suites/workflow/utils/submit-form-step.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 { updateFeatureFlag } from 'test/integration/metadata/suites/utils/update-feature-flag.util';+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';+import { FeatureFlagKey } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++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 DeleteWorkflowActionHandlerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/workflow/services/delete-workflow-action-handler.service';+import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';++const SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);+const PREFIX = `Removed app workflow ${randomUUID()}`;+const APP_ID = randomUUID();+const ROLE_ID = randomUUID();+const COMPANY_PERMISSION_ID = randomUUID();+const FUNCTION_ID = randomUUID();++const KEPT_COMPANY = `${PREFIX} kept company`;++const FORM_WORKFLOW = buildTestApplicationWorkflow(`${PREFIX} form`, [+ formStep(),+ createCompanyStep(`${PREFIX} form company`),+]);+const SECOND_FORM_WORKFLOW = buildTestApplicationWorkflow(+ `${PREFIX} second form`,+ [+ formStep(),+ logicFunctionStep(FUNCTION_ID),+ createCompanyStep(`${PREFIX} second form company`),+ ],+);+const KEPT_WORKFLOW = buildTestApplicationWorkflow(`${PREFIX} kept`, [+ formStep(),+ createCompanyStep(KEPT_COMPANY),+]);++const buildManifest = (workflows: TestApplicationWorkflow[]) =>+ buildTestApplicationManifest({+ applicationUniversalIdentifier: APP_ID,+ roleUniversalIdentifier: ROLE_ID,+ companyPermissionUniversalIdentifier: COMPANY_PERMISSION_ID,+ logicFunctionUniversalIdentifier: FUNCTION_ID,+ workflows,+ });++const createdWorkflowRunIds: string[] = [];+const versionIdByWorkflowIdentifier = new Map<string, string>();++const runWorkflowAndWaitForFirstStep = async (+ workflow: TestApplicationWorkflow,+): Promise<string> => {+ const response = await runCoreWorkflowVersion(+ versionIdByWorkflowIdentifier.get(workflow.universalIdentifier) ?? '',+ );++ expect(response.body.errors).toBeUndefined();++ const workflowRunId = response.body.data.runCoreWorkflowVersion.workflowRunId;++ createdWorkflowRunIds.push(workflowRunId);++ await waitForTestWorkflowRun(+ workflowRunId,+ ({ state }) =>+ state?.stepInfos?.[workflow.steps[0].universalIdentifier]?.status ===+ 'PENDING',+ );++ return workflowRunId;+};++const expectWaiting = async (+ workflowRunId: string,+ workflow: TestApplicationWorkflow,+) => {+ const workflowRun = await findTestWorkflowRun(workflowRunId);++ expect(workflowRun?.status).toBe(WorkflowRunStatus.RUNNING);+ expect(+ workflowRun?.state.stepInfos[workflow.steps[0].universalIdentifier]?.status,+ ).toBe('PENDING');+};++describe('removing workflows from an application manifest', () => {+ let formRunId: string;+ let secondFormRunId: string;+ let keptRunId: string;++ beforeAll(async () => {+ await updateFeatureFlag({+ featureFlag: FeatureFlagKey.IS_APPLICATION_WORKFLOWS_ENABLED,+ value: true,+ expectToFail: false,+ });+ await setupApplicationForSync({+ applicationUniversalIdentifier: APP_ID,+ name: 'Application workflow removal',+ description: 'Application whose workflows are removed from its manifest',+ sourcePath: 'application-workflow-removal',+ });+ jest.useRealTimers();++ const installation = await syncApplication({+ manifest: buildManifest([+ FORM_WORKFLOW,+ SECOND_FORM_WORKFLOW,+ KEPT_WORKFLOW,+ ]),+ });++ expect(installation.errors).toBeUndefined();++ for (const workflow of [+ FORM_WORKFLOW,+ SECOND_FORM_WORKFLOW,+ KEPT_WORKFLOW,+ ]) {+ const versionId = await findTestWorkflowVersionId({+ applicationUniversalIdentifier: APP_ID,+ workflow,+ });++ if (!isDefined(versionId)) {+ throw new Error(`${workflow.name} was not installed`);+ }++ versionIdByWorkflowIdentifier.set(+ workflow.universalIdentifier,+ versionId,+ );+ }++ formRunId = await runWorkflowAndWaitForFirstStep(FORM_WORKFLOW);+ secondFormRunId =+ await runWorkflowAndWaitForFirstStep(SECOND_FORM_WORKFLOW);+ keptRunId = await runWorkflowAndWaitForFirstStep(KEPT_WORKFLOW);+ }, 180000);++ afterAll(async () => {+ await globalThis.testDataSource.query(+ `DELETE FROM "${SCHEMA}"."workflowRun" WHERE id = ANY($1)`,+ [createdWorkflowRunIds],+ );+ await globalThis.testDataSource.query(+ `DELETE FROM "${SCHEMA}"."company" WHERE name LIKE $1`,+ [`${PREFIX}%`],+ );+ await cleanupApplicationAndAppRegistration({+ applicationUniversalIdentifier: APP_ID,+ });+ await updateFeatureFlag({+ featureFlag: FeatureFlagKey.IS_APPLICATION_WORKFLOWS_ENABLED,+ value: false,+ expectToFail: false,+ });+ jest.useFakeTimers();+ });++ it('leaves runs alone when an update keeps every workflow', async () => {+ const update = await syncApplication({+ manifest: buildManifest([+ FORM_WORKFLOW,+ SECOND_FORM_WORKFLOW,+ { ...KEPT_WORKFLOW, name: `${KEPT_WORKFLOW.name} renamed` },+ ]),+ });++ expect(update.errors).toBeUndefined();+ await expectWaiting(formRunId, FORM_WORKFLOW);+ await expectWaiting(secondFormRunId, SECOND_FORM_WORKFLOW);+ await expectWaiting(keptRunId, KEPT_WORKFLOW);+ }, 120000);++ it('keeps workflows and runs when the removal fails after deleting a workflow', async () => {+ const deleteWorkflowActionHandler =+ getAppProviderByClassName<DeleteWorkflowActionHandlerService>(+ 'DeleteWorkflowActionHandlerService',+ );+ const deleteWorkflow = deleteWorkflowActionHandler.executeForMetadata.bind(+ deleteWorkflowActionHandler,+ );+ const deleteSpy = jest+ .spyOn(deleteWorkflowActionHandler, 'executeForMetadata')+ .mockImplementationOnce(async (context) => {+ await deleteWorkflow(context);+ throw new Error('Simulated sync failure after a workflow delete');+ });++ try {+ const failedRemoval = await syncApplication({+ manifest: buildManifest([KEPT_WORKFLOW]),+ expectToFail: true,+ });++ expect(failedRemoval.errors).toBeDefined();+ } finally {+ deleteSpy.mockRestore();+ }++ expect(await countCoreWorkflows(FORM_WORKFLOW)).toBe(1);+ expect(await countCoreWorkflows(SECOND_FORM_WORKFLOW)).toBe(1);++ await new Promise((resolve) => setTimeout(resolve, 2000));++ await expectWaiting(formRunId, FORM_WORKFLOW);+ await expectWaiting(secondFormRunId, SECOND_FORM_WORKFLOW);+ }, 120000);++ it('deletes the omitted workflows with their version and runs, and keeps the application function', async () => {+ const removal = await syncApplication({+ manifest: buildManifest([KEPT_WORKFLOW]),+ });++ expect(removal.errors).toBeUndefined();++ for (const workflow of [FORM_WORKFLOW, SECOND_FORM_WORKFLOW]) {+ expect(await countCoreWorkflows(workflow)).toBe(0);+ expect(+ await findTestWorkflowVersionId({+ applicationUniversalIdentifier: APP_ID,+ workflow,+ }),+ ).toBeUndefined();+ }++ expect(await countTestWorkflowRuns([formRunId, secondFormRunId])).toBe(0);+ expect(await countTestWorkflowRuns([keptRunId])).toBe(1);++ const [{ count: applicationFunctionCount }] =+ await globalThis.testDataSource.query(+ `SELECT COUNT(*)::int AS count FROM core."logicFunction"+ WHERE "universalIdentifier" = $1 AND "workspaceId" = $2`,+ [FUNCTION_ID, SEED_APPLE_WORKSPACE_ID],+ );++ expect(applicationFunctionCount).toBe(1);+ }, 120000);++ it('keeps the remaining workflow runnable', async () => {+ await expectWaiting(keptRunId, KEPT_WORKFLOW);++ const submission = await submitFormStep({+ workflowRunId: keptRunId,+ stepId: KEPT_WORKFLOW.steps[0].universalIdentifier,+ response: { note: 'Still runnable' },+ });++ expect(submission.body.errors).toBeUndefined();++ await waitForTestWorkflowRun(+ keptRunId,+ ({ status }) => status === WorkflowRunStatus.COMPLETED,+ );++ expect(await countTestCompanies(KEPT_COMPANY)).toBe(1);+ }, 120000);++ it('makes no change when the same manifest is synced again', async () => {+ const runsBefore = await Promise.all(+ createdWorkflowRunIds.map(findTestWorkflowRun),+ );++ const repeat = await syncApplication({+ manifest: buildManifest([KEPT_WORKFLOW]),+ });++ expect(repeat.errors).toBeUndefined();+ expect(repeat.data.syncApplication.actions).toEqual([]);+ expect(+ await Promise.all(createdWorkflowRunIds.map(findTestWorkflowRun)),+ ).toEqual(runsBefore);+ }, 120000);+});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.tsindex cb522207e6c..2467c24b849 100644--- 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@@ -124,13 +124,17 @@ const findDefinitions = () =>[WORKSPACE_ID, WORKFLOW_ID, FUNCTION_ID],);+const createdWorkflowRunIds: string[] = [];+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 workflowRunId = response.body.data.runCoreWorkflowVersion.workflowRunId;+ createdWorkflowRunIds.push(workflowRunId);+ return workflowRunId;};const findRun = async (runId: string): Promise<WorkflowRunWorkspaceEntity> => {@@ -201,8 +205,8 @@ describe('application-owned core workflows', () => {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],+ `DELETE FROM "${SCHEMA}"."workflowRun" WHERE id = ANY($1)`,+ [createdWorkflowRunIds],);await cleanupApplicationAndAppRegistration({applicationUniversalIdentifier: APP_ID,@@ -218,7 +222,7 @@ describe('application-owned core workflows', () => {jest.useFakeTimers();});- it('installs, upgrades through additive pre-install sync, and protects saved runs and app-owned definitions', async () => {+ it('installs, upgrades through additive pre-install sync, protects saved runs and app-owned definitions, then removes omitted workflows', async () => {const initial = await syncApplication({ manifest: MANIFEST });expect(initial.errors).toBeUndefined();const [referencingVersion] = await globalThis.testDataSource.query(@@ -338,11 +342,9 @@ describe('application-owned core workflows', () => {inferDeletionFromMissingEntities: false,});expect(additive.errors).toBeUndefined();- const removing = await syncApplication({- manifest: missingWorkflow,- expectToFail: true,- });- expect(removing.errors).toBeDefined();expect(await findDefinitions()).toEqual(updatedDefinitions);+ const removing = await syncApplication({ manifest: missingWorkflow });+ expect(removing.errors).toBeUndefined();+ expect(await findDefinitions()).toEqual([]);}, 90000);});