The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Create, rename, duplicate and delete workflows in core only (#27882)
Thomas Trompette53a2c844873f
diff --git a/packages/twenty-server/docs/WORKFLOW_CORE_EXECUTION.md b/packages/twenty-server/docs/WORKFLOW_CORE_EXECUTION.mdindex 601c348cb57..1cbad28f229 100644--- a/packages/twenty-server/docs/WORKFLOW_CORE_EXECUTION.md+++ b/packages/twenty-server/docs/WORKFLOW_CORE_EXECUTION.md@@ -10,7 +10,7 @@ Workflow execution uses `core.workflow`, `core.workflowVersion`, and the persist| `core.workflowVersion.coreWorkflowId` | Authoritative version parent, scoped to the same workspace. || `core.workflow.workspaceWorkflowId` | Durable alias for existing webhook URLs and historical billing spender IDs. Keep this alias for the lifetime of those URLs and billing identities. || `core.workflowVersion.workspaceWorkflowVersionId` | Durable alias for legacy run requests and pinned queued payloads. Keep it while any legacy callers or queued jobs can exist. |-| `core.workflowVersion.workflowId` | Nullable legacy parent alias maintained for rollback projections. It is not the execution parent. |+| `core.workflowVersion.workflowId` | Nullable legacy parent alias, equal to the workflow's `workspaceWorkflowId`. Null on workflows created without a workspace alias. It is not the execution parent. || `workflowRun.coreWorkflowId`, `workflowRun.coreWorkflowVersionId` | Authoritative identities recorded when a run is created and backfilled for existing runs. || `workflowRun.workflowId`, `workflowRun.workflowVersionId` | Nullable projection relations. Mirrorless runs leave both null. || `workflowRun.state.flow` | Captured trigger and steps. Startup, retry, delay, and form continuation use this snapshot rather than a subsequently edited definition. |@@ -34,9 +34,7 @@ Cron workers share the historical workflow lock key for mapped workflows and the## Writes-Dedicated legacy builder and lifecycle mutations mirror execution changes within their transactions. Generated single and bulk workflow creation use the existing workflow writer to create the core parent before inserting initial versions. Version mirroring resolves an existing parent. Initial versions and core-created drafts persist the durable version alias synchronously. Generic workflow mutations cannot change execution links directly; generic version content and lifecycle writes remain restricted to dedicated mutations. Allowed workflow updates, deletion, and restoration synchronize core before returning.--Core writes use workspace repositories for outgoing projection changes, preserving database events. The reverse workflow listener uses event IDs to lock and read current workspace records. It does not apply historical event snapshots, preventing a delayed update or delete event from overwriting a newer projection.+Workflow creation, rename, duplication, deletion, version content, drafts, activation and deactivation write core only. The workspace `workflow`, `workflowVersion` and `workflowAutomatedTrigger` objects are no longer written; existing rows stay as data. Workflows created through core, and their versions, have no workspace alias. Generic workflow mutations cannot change execution links or version content.## Deployment and rollback@@ -45,6 +43,6 @@ Core writes use workspace repositories for outgoing projection changes, preservi3. With that barrier held, run the 2.42 parent-link repair, shared version-alias backfill, workflow execution mapping backfill, and projection-nullability command. Dry-run and resolve reported mapping conflicts, then commit and verify the backfill. The execution backfill requires the shared aliases to be populated, then validates pending runs and published pointers transactionally; it does not overwrite or independently populate version aliases.4. Deploy upgraded workers and queue consumers before the API and scheduler producers. Keep the barrier until every definition writer uses synchronous durable mappings and every consumer supports core-only execution. Then resume traffic and consumers. A UI flag change does not establish this barrier. A zero-downtime rollout instead requires a separate preparatory release that maintains the durable mappings on every writer before the backfill; this PR does not assume that release already exists.5. Verify old webhook URLs, legacy version requests, queued runs, delayed jobs, form continuations, and cron overlap. No queue purge or delayed-job renaming is required. Compatible envelopes allow old queued work to drain after the cutover; do not resume old definition writers or introduce mirrorless producers while old consumers remain.-6. The UI flag can move ON → OFF → ON independently. Preserve synchronous projections during the rollback window; run execution remains core-only throughout. Rolling the binaries back also requires pausing writes and consumers and re-establishing mappings before the next core-only cutover.+6. Workspace projections are no longer maintained. Rolling the binaries back to a release that reads or requires them breaks editing workflows created afterwards, since those have no workspace rows.Do not drop legacy payload decoding or aliases merely because the UI rollback window has ended. Delayed jobs and integrations can outlive that window. Removing workspace workflow objects, rebuilding workflow show pages, rekeying MCP tools, and migrating historical usage are separate changes.diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.tsindex efbbf05acdb..e35faa3a261 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.ts@@ -3,7 +3,6 @@ import { Args, Mutation, Query } from '@nestjs/graphql';import { msg } from '@lingui/core/macro';import { PermissionFlagType } from 'twenty-shared/constants';-import { type ActorMetadata } from 'twenty-shared/types';import { CoreResolver } from 'src/engine/api/graphql/graphql-config/decorators/core-resolver.decorator';import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';@@ -79,13 +78,11 @@ export class CoreWorkflowResolver {private readonly coreWorkflowVersionListService: CoreWorkflowVersionListService,) {}- private resolveCreatedByOrThrow(principal: {+ private assertWorkflowActorOrThrow(principal: {workspaceMember?: WorkspaceMemberWorkspaceEntity;application?: FlatApplication;- }): ActorMetadata {- const createdBy = buildActorMetadataFromPrincipal(principal);-- if (!isDefined(createdBy)) {+ }): void {+ if (!isDefined(buildActorMetadataFromPrincipal(principal))) {throw new WorkflowQueryValidationException('No authenticated actor to attribute the workflow to',WorkflowQueryValidationExceptionCode.FORBIDDEN,@@ -94,8 +91,6 @@ export class CoreWorkflowResolver {},);}-- return createdBy;}@Mutation(() => CoreWorkflowDTO, { nullable: true })@@ -147,9 +142,10 @@ export class CoreWorkflowResolver {coreWorkflowVersionIdToCopy,}: DuplicateCoreWorkflowInput,): Promise<CoreWorkflowDTO> {+ this.assertWorkflowActorOrThrow({ workspaceMember, application });+return this.coreWorkflowMutationWorkspaceService.duplicateWorkflow({workspaceId,- createdBy: this.resolveCreatedByOrThrow({ workspaceMember, application }),userWorkspaceId,coreWorkflowIdToDuplicate,coreWorkflowVersionIdToCopy,@@ -168,9 +164,10 @@ export class CoreWorkflowResolver {userWorkspaceId: string | undefined,@Args('input') input: CreateCoreWorkflowInput,): Promise<CoreWorkflowDTO> {+ this.assertWorkflowActorOrThrow({ workspaceMember, application });+return this.coreWorkflowMutationWorkspaceService.createWorkflow({workspaceId,- createdBy: this.resolveCreatedByOrThrow({ workspaceMember, application }),userWorkspaceId,...input,});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.tsindex 09039081778..6ae96248568 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@@ -100,37 +100,4 @@ export class CoreWorkflowIdResolutionService {return coreWorkflow;}-- async resolveWorkspaceWorkflowIdOrThrow({- workspaceId,- userWorkspaceId,- coreWorkflowId,- }: {- workspaceId: string;- userWorkspaceId: string | undefined;- coreWorkflowId: string;- }): Promise<{- coreWorkflow: WorkflowEntity;- workspaceWorkflowId: string;- }> {- const coreWorkflow = await this.resolveCoreWorkflowOrThrow({- workspaceId,- userWorkspaceId,- coreWorkflowId,- });-- const workspaceWorkflowId = coreWorkflow.workspaceWorkflowId;-- if (!isDefined(workspaceWorkflowId)) {- throw new WorkflowQueryValidationException(- `Core workflow '${coreWorkflowId}' has no workspace mirror row`,- WorkflowQueryValidationExceptionCode.FORBIDDEN,- {- userFriendlyMessage: msg`Workflow is not correctly linked to its mirror`,- },- );- }-- return { 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.tsindex b549e83ae20..fde4fc695e1 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@@ -10,11 +10,10 @@ import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspaimport { Equal, In, IsNull, Or } from 'typeorm';import { msg } from '@lingui/core/macro';-import { type ActorMetadata, WorkflowVisibility } from 'twenty-shared/types';+import { WorkflowVisibility } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';import { v4 as uuidv4 } from 'uuid';-import { RecordPositionService } from 'src/engine/core-modules/record-position/services/record-position.service';import { type CoreWorkflowDTO } from 'src/engine/core-modules/workflow/dtos/core-workflow.dto';import { type DeletedCoreWorkflowDTO } from 'src/engine/core-modules/workflow/dtos/deleted-core-workflow.dto';import { type DiscardCoreWorkflowDraftInput } from 'src/engine/core-modules/workflow/dtos/discard-core-workflow-draft.input';@@ -26,24 +25,18 @@ import {import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';import { CommandMenuItemService } from 'src/engine/metadata-modules/command-menu-item/command-menu-item.service';import { getWorkflowCommandMenuItemLabel } from 'src/modules/workflow/workflow-trigger/utils/get-workflow-command-menu-item-label.util';-import { CoreWorkflowIdResolutionService } from 'src/engine/core-modules/workflow/services/core-workflow-id-resolution.service';import { CoreWorkflowListService } from 'src/engine/core-modules/workflow/services/core-workflow-list.service';import { CoreWorkflowVersionWriteService } from 'src/engine/core-modules/workflow/services/core-workflow-version-write.service';import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';import { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';import { WorkflowCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-core-sync.service';import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';-import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';import {WorkflowQueryValidationException,WorkflowQueryValidationExceptionCode,} from 'src/modules/workflow/common/exceptions/workflow-query-validation.exception';-import { type WorkflowVersionWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-version.workspace-entity';-import { type WorkflowWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow.workspace-entity';-import { WorkflowCommonWorkspaceService } from 'src/modules/workflow/common/workspace-services/workflow-common.workspace-service';import { remapDuplicatedStepDestinations } from 'src/modules/workflow/workflow-builder/utils/remap-duplicated-step-destinations.util';import { WorkflowVersionStepOperationsWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service';import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';@@ -59,8 +52,6 @@ export class CoreWorkflowMutationWorkspaceService {private readonly coreWorkflowRepository: WorkspaceScopedRepository<WorkflowEntity>,private readonly workflowCoreSyncService: WorkflowCoreSyncService,private readonly workflowVersionCoreSyncService: WorkflowVersionCoreSyncService,- private readonly workflowCommonWorkspaceService: WorkflowCommonWorkspaceService,- private readonly coreWorkflowIdResolutionService: CoreWorkflowIdResolutionService,private readonly coreWorkflowAccessService: CoreWorkflowAccessService,private readonly commandMenuItemService: CommandMenuItemService,private readonly coreWorkflowListService: CoreWorkflowListService,@@ -68,8 +59,6 @@ export class CoreWorkflowMutationWorkspaceService {private readonly workflowVersionStepOperationsWorkspaceService: WorkflowVersionStepOperationsWorkspaceService,@InjectWorkspaceScopedRepository(WorkflowVersionEntity)private readonly coreWorkflowVersionRepository: WorkspaceScopedRepository<WorkflowVersionEntity>,- private readonly workspaceOrmManager: WorkspaceOrmManager,- private readonly recordPositionService: RecordPositionService,private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,private readonly applicationService: ApplicationService,@@ -115,13 +104,11 @@ export class CoreWorkflowMutationWorkspaceService {async duplicateWorkflow({workspaceId,- createdBy,userWorkspaceId,coreWorkflowIdToDuplicate,coreWorkflowVersionIdToCopy,}: {workspaceId: string;- createdBy: ActorMetadata;userWorkspaceId: string | undefined;coreWorkflowIdToDuplicate: string;coreWorkflowVersionIdToCopy: string;@@ -178,7 +165,6 @@ export class CoreWorkflowMutationWorkspaceService {const duplicatedWorkflow = await this.createWorkflow({workspaceId,- createdBy,userWorkspaceId,name: `${sourceCoreWorkflow.name ?? ''} (Duplicate)`,// duplicating a private workflow must not publish it to the workspace@@ -353,11 +339,6 @@ export class CoreWorkflowMutationWorkspaceService {coreWorkflowIds: [coreWorkflowId],});- const { workspaceWorkflowId } =- await this.coreWorkflowIdResolutionService.resolveWorkspaceWorkflowIdOrThrow(- { workspaceId, userWorkspaceId, coreWorkflowId },- );-const { flatWorkflowMaps } =await this.flatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps({ workspaceId, flatMapsKeys: ['flatWorkflowMaps'] },@@ -381,14 +362,6 @@ export class CoreWorkflowMutationWorkspaceService {},});- await this.workspaceOrmManager.executeInWorkspaceContext(async () => {- await this.workspaceOrmManager- .getRepository<WorkflowWorkspaceEntity>('workflow', {- shouldBypassPermissionChecks: true,- })- .update({ id: workspaceWorkflowId }, { name });- }, buildSystemAuthContext(workspaceId));-await this.syncCommandMenuItemLabelFromCore({workspaceId,coreWorkflowId,@@ -447,13 +420,11 @@ export class CoreWorkflowMutationWorkspaceService {async createWorkflow({workspaceId,- createdBy,userWorkspaceId,name,visibility,}: {workspaceId: string;- createdBy: ActorMetadata;userWorkspaceId: string | undefined;name?: string;visibility?: WorkflowVisibility;@@ -463,17 +434,13 @@ export class CoreWorkflowMutationWorkspaceService {workspaceId,);- const authContext = buildSystemAuthContext(workspaceId);-- const workspaceWorkflowId = uuidv4();-const createdAt = new Date().toISOString();const coreWorkflow = {id: uuidv4(),name: name ?? null,universalIdentifier: uuidv4(),- workspaceWorkflowId,+ workspaceWorkflowId: null,isSystem: false,visibility: visibility ?? WorkflowVisibility.WORKSPACE,createdByUserWorkspaceId: userWorkspaceId ?? null,@@ -511,42 +478,20 @@ export class CoreWorkflowMutationWorkspaceService {});try {- await this.workspaceOrmManager.executeInWorkspaceContext(async () => {- const workflowRepository =- this.workspaceOrmManager.getRepository<WorkflowWorkspaceEntity>(- 'workflow',- { shouldBypassPermissionChecks: true },- );-- const position = await this.recordPositionService.buildRecordPosition({- value: 'first',- objectMetadata: {- isCustom: false,- nameSingular: 'workflow',- },+ await this.coreWorkflowVersionWriteService.createDraftCoreWorkflowVersion(+ {workspaceId,- });-- await workflowRepository.insert({- id: workspaceWorkflowId,- name: name ?? null,- position,coreWorkflowId: coreWorkflow.id,- createdBy,- });- }, authContext);-- await this.workflowVersionCoreSyncService.createInitialDraftVersionForWorkflow(- workspaceId,- workspaceWorkflowId,+ workspaceWorkflowId: null,+ trigger: null,+ steps: null,+ },);} catch (error) {try {- await this.rollbackCreatedWorkflow(- workspaceId,+ await this.workflowCoreSyncService.deleteFromCore(workspaceId, [coreWorkflow.id,- workspaceWorkflowId,- );+ ]);} catch (rollbackError) {this.logger.error(rollbackError);}@@ -560,7 +505,7 @@ export class CoreWorkflowMutationWorkspaceService {statuses: [WorkflowStatus.DRAFT],lastPublishedVersionId: null,applicationId,- workspaceWorkflowId,+ workspaceWorkflowId: null,isSystem: coreWorkflow.isSystem,visibility: coreWorkflow.visibility,canChangeVisibility: true,@@ -592,53 +537,10 @@ export class CoreWorkflowMutationWorkspaceService {},);- const mirrorWorkflows = await this.findMirrorWorkflowsToDelete({- workspaceId,- coreWorkflowIds,- });-- const mirrorWorkflowIdByCoreWorkflowId = new Map(- mirrorWorkflows.flatMap(({ id, coreWorkflowId }) =>- isDefined(coreWorkflowId) ? [[coreWorkflowId, id] as const] : [],- ),- );-const deletedCoreWorkflows = coreWorkflowsToDelete.map(- ({ id, workspaceWorkflowId }) => ({- id,- workspaceWorkflowId:- workspaceWorkflowId ??- mirrorWorkflowIdByCoreWorkflowId.get(id) ??- null,- }),+ ({ id, workspaceWorkflowId }) => ({ id, workspaceWorkflowId }),);- const mirrorWorkflowIds = [- ...new Set([- ...coreWorkflowsToDelete- .map(({ workspaceWorkflowId }) => workspaceWorkflowId)- .filter(isDefined),- ...mirrorWorkflows.map(({ id }) => id),- ]),- ];-- if (mirrorWorkflowIds.length > 0) {- const authContext = buildSystemAuthContext(workspaceId);-- await this.workspaceOrmManager.executeInWorkspaceContext(async () => {- await this.workspaceOrmManager- .getRepository<WorkflowWorkspaceEntity>('workflow', {- shouldBypassPermissionChecks: true,- })- .softDelete({ id: In(mirrorWorkflowIds) });- }, authContext);-- await this.workflowCommonWorkspaceService.deleteWorkflowSubEntities({- workflowIds: mirrorWorkflowIds,- workspaceId,- });- }-await this.workflowCoreSyncService.deleteFromCore(workspaceId,coreWorkflowIds,@@ -647,28 +549,6 @@ export class CoreWorkflowMutationWorkspaceService {return deletedCoreWorkflows;}- private async findMirrorWorkflowsToDelete({- workspaceId,- coreWorkflowIds,- }: {- workspaceId: string;- coreWorkflowIds: string[];- }): Promise<Pick<WorkflowWorkspaceEntity, 'id' | 'coreWorkflowId'>[]> {- return this.workspaceOrmManager.executeInWorkspaceContext(- async () =>- this.workspaceOrmManager- .getRepository<WorkflowWorkspaceEntity>('workflow', {- shouldBypassPermissionChecks: true,- })- .find({- where: { coreWorkflowId: In(coreWorkflowIds) },- select: { id: true, coreWorkflowId: true },- withDeleted: true,- }),- buildSystemAuthContext(workspaceId),- );- }-async discardDraftVersion({workspaceId,userWorkspaceId,@@ -814,36 +694,4 @@ export class CoreWorkflowMutationWorkspaceService {coreWorkflowId,});}-- private async rollbackCreatedWorkflow(- workspaceId: string,- coreWorkflowId: string,- workspaceWorkflowId: string | undefined,- ): Promise<void> {- if (isDefined(workspaceWorkflowId)) {- await this.workspaceOrmManager.executeInWorkspaceContext(async () => {- const workflowVersionRepository =- this.workspaceOrmManager.getRepository<WorkflowVersionWorkspaceEntity>(- 'workflowVersion',- { shouldBypassPermissionChecks: true },- );-- await workflowVersionRepository.delete({- workflowId: workspaceWorkflowId,- });-- const workflowRepository =- this.workspaceOrmManager.getRepository<WorkflowWorkspaceEntity>(- 'workflow',- { shouldBypassPermissionChecks: true },- );-- await workflowRepository.delete({ id: workspaceWorkflowId });- }, buildSystemAuthContext(workspaceId));- }-- await this.workflowCoreSyncService.deleteFromCore(workspaceId, [- coreWorkflowId,- ]);- }}diff --git a/packages/twenty-server/src/modules/workflow/common/workspace-services/workflow-common.workspace-service.ts b/packages/twenty-server/src/modules/workflow/common/workspace-services/workflow-common.workspace-service.tsindex b7bc11ae1d3..3a73cdbb8f5 100644--- a/packages/twenty-server/src/modules/workflow/common/workspace-services/workflow-common.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/common/workspace-services/workflow-common.workspace-service.ts@@ -1,32 +1,19 @@-import { WorkflowStatus } from 'src/engine/core-modules/workflow/enums/workflow-status.enum';-import { WorkflowCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-core-sync.service';import { Injectable } from '@nestjs/common';import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';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';import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';-import { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace-repository';-import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import {type ObjectMetadataInfo,WorkflowMetadataReadService,} from 'src/modules/workflow/common/workspace-services/workflow-metadata-read.workspace-service';-import { type WorkflowAutomatedTriggerWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-automated-trigger.workspace-entity';-import {- WorkflowVersionStatus,- type WorkflowVersionWorkspaceEntity,-} from 'src/modules/workflow/common/standard-objects/workflow-version.workspace-entity';-import { type WorkflowWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow.workspace-entity';export type { ObjectMetadataInfo };@Injectable()export class WorkflowCommonWorkspaceService {constructor(- private readonly workflowCoreSyncService: WorkflowCoreSyncService,- private readonly workspaceOrmManager: WorkspaceOrmManager,private readonly workflowMetadataReadService: WorkflowMetadataReadService,) {}@@ -60,94 +47,4 @@ export class WorkflowCommonWorkspaceService {workspaceId,);}-- async deleteWorkflowSubEntities({- workflowIds,- workspaceId,- }: {- workflowIds: string[];- workspaceId: string;- }): Promise<void> {- await this.workspaceOrmManager.executeInWorkspaceContext(async () => {- const workflowVersionRepository =- this.workspaceOrmManager.getRepository<WorkflowVersionWorkspaceEntity>(- 'workflowVersion',- { shouldBypassPermissionChecks: true },- );-- const workflowAutomatedTriggerRepository =- this.workspaceOrmManager.getRepository<WorkflowAutomatedTriggerWorkspaceEntity>(- 'workflowAutomatedTrigger',- { shouldBypassPermissionChecks: true },- );-- for (const workflowId of workflowIds) {- await workflowAutomatedTriggerRepository.softDelete({ workflowId });- await workflowVersionRepository.softDelete({ workflowId });-- await this.deactivateVersionOnDelete({- workflowVersionRepository,- workflowId,- });-- await this.workflowCoreSyncService.reconcileWorkspaceWorkflows(- workspaceId,- [workflowId],- );- }- }, buildSystemAuthContext(workspaceId));- }-- private async deactivateVersionOnDelete({- workflowVersionRepository,- workflowId,- }: {- workflowVersionRepository: WorkspaceRepository<WorkflowVersionWorkspaceEntity>;- workflowId: string;- }) {- const workflowVersions = await workflowVersionRepository.find({- where: { workflowId },- withDeleted: true,- });-- await this.workspaceOrmManager.runInWorkspaceTransaction(- async ({ getRepository }) => {- const workflowRepository = getRepository<WorkflowWorkspaceEntity>(- 'workflow',- { shouldBypassPermissionChecks: true },- );- const transactionalWorkflowVersionRepository =- getRepository<WorkflowVersionWorkspaceEntity>('workflowVersion', {- shouldBypassPermissionChecks: true,- });-- const workflow = await workflowRepository.findOne({- where: { id: workflowId },- withDeleted: true,- });-- if (workflow?.statuses?.includes(WorkflowStatus.ACTIVE)) {- const newStatuses = [- ...workflow.statuses.filter(- (status) => status !== WorkflowStatus.ACTIVE,- ),- WorkflowStatus.DEACTIVATED,- ];-- await workflowRepository.update(workflowId, {- statuses: newStatuses,- });- }-- for (const workflowVersion of workflowVersions) {- if (workflowVersion.status === WorkflowVersionStatus.ACTIVE) {- await transactionalWorkflowVersionRepository.update(- workflowVersion.id,- { status: WorkflowVersionStatus.DEACTIVATED },- );- }- }- },- );- }}diff --git a/packages/twenty-server/src/modules/workflow/workflow-tools/constants/default-agent-workflow-actor.constant.ts b/packages/twenty-server/src/modules/workflow/workflow-tools/constants/default-agent-workflow-actor.constant.tsdeleted file mode 100644index 3e693ddf5f2..00000000000--- a/packages/twenty-server/src/modules/workflow/workflow-tools/constants/default-agent-workflow-actor.constant.ts+++ /dev/null@@ -1,8 +0,0 @@-import { type ActorMetadata, FieldActorSource } from 'twenty-shared/types';--export const DEFAULT_AGENT_WORKFLOW_ACTOR: ActorMetadata = {- source: FieldActorSource.AGENT,- workspaceMemberId: null,- name: 'Agent',- context: {},-};diff --git a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.ts b/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.tsindex d988850e77c..bb2e0461c61 100644--- a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.ts@@ -13,7 +13,6 @@ import {WorkflowVersionStepExceptionCode,} from 'src/modules/workflow/common/exceptions/workflow-version-step.exception';import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';-import { DEFAULT_AGENT_WORKFLOW_ACTOR } from 'src/modules/workflow/workflow-tools/constants/default-agent-workflow-actor.constant';import { workflowStepConnectionOptionsSchema } from 'src/modules/workflow/workflow-tools/tools/schemas/workflow-step-connection-options.schema';import {type WorkflowToolContext,@@ -125,7 +124,6 @@ Call validate_workflow once when the workflow is complete, before activating.`,const coreWorkflow =await deps.coreWorkflowMutationService.createWorkflow({workspaceId,- createdBy: context.actorContext ?? DEFAULT_AGENT_WORKFLOW_ACTOR,userWorkspaceId: undefined,name: parameters.name,});diff --git a/packages/twenty-server/test/integration/ai/suites/workflow-tools-core-ids.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/workflow-tools-core-ids.integration-spec.tsindex 72a45c9352b..d87e48dcf56 100644--- a/packages/twenty-server/test/integration/ai/suites/workflow-tools-core-ids.integration-spec.ts+++ b/packages/twenty-server/test/integration/ai/suites/workflow-tools-core-ids.integration-spec.ts@@ -169,16 +169,20 @@ describe('workflow MCP tools on core identities (integration)', () => {expect(coreWorkflowVersionId).toBeDefined();});- it('should key the returned identifiers on core rows whose ids differ from the workspace mirrors', async () => {+ it('should create the workflow without workspace rows', async () => {const coreWorkflow = await readCoreWorkflowRow(coreWorkflowId);const coreVersion = await readCoreVersionRow(coreWorkflowVersionId);- expect(coreWorkflow.workspaceWorkflowId).toBeDefined();- expect(coreWorkflow.workspaceWorkflowId).not.toBe(coreWorkflowId);- expect(coreVersion.workspaceWorkflowVersionId).toBeDefined();- expect(coreVersion.workspaceWorkflowVersionId).not.toBe(- coreWorkflowVersionId,+ expect(coreWorkflow.workspaceWorkflowId).toBeNull();+ expect(coreVersion.workspaceWorkflowVersionId).toBeNull();++ const [{ workspaceRowCount }] = await global.testDataSource.query(+ `SELECT (SELECT count(*) FROM "${TEST_WORKSPACE_SCHEMA}"."workflow" WHERE "coreWorkflowId" = $1)::int+ + (SELECT count(*) FROM "${TEST_WORKSPACE_SCHEMA}"."workflowVersion" WHERE "coreWorkflowVersionId" = $2)::int AS "workspaceRowCount"`,+ [coreWorkflowId, coreWorkflowVersionId],);++ expect(workspaceRowCount).toBe(0);});it('should preserve the iterator loop connection and the step after the loop', async () => {@@ -281,24 +285,6 @@ describe('workflow MCP tools on core identities (integration)', () => {).toBe(renamedStepName);});- it('should read core content even after the workspace mirror content diverges', async () => {- const coreVersion = await readCoreVersionRow(coreWorkflowVersionId);-- await global.testDataSource.query(- `UPDATE "${TEST_WORKSPACE_SCHEMA}"."workflowVersion"- SET steps = '[]'::jsonb WHERE id = $1`,- [coreVersion.workspaceWorkflowVersionId],- );-- const current = await callWorkflowTool<{- success: boolean;- workflowVersion: { steps: { id: string }[] };- }>('get_workflow_current_version', { coreWorkflowId });-- expect(current.success).toBe(true);- expect(current.workflowVersion.steps).toHaveLength(3);- });-it('should validate and activate using the core version id', async () => {const validated = await callWorkflowTool<{success: boolean;@@ -331,62 +317,6 @@ describe('workflow MCP tools on core identities (integration)', () => {});});- describe('reads without a workspace definition mirror', () => {- let coreWorkflowId: string;- let coreWorkflowVersionId: string;-- beforeAll(async () => {- const created = await callWorkflowTool<{- result: { coreWorkflowId: string; coreWorkflowVersionId: string };- }>('create_complete_workflow', {- name: `Mirrorless core workflow ${randomUUID()}`,- trigger: buildManualTrigger(),- steps: [buildCodeFreeStep(randomUUID(), 'Only step')],- edges: [],- });-- coreWorkflowId = created.result.coreWorkflowId;- coreWorkflowVersionId = created.result.coreWorkflowVersionId;- coreWorkflowIdsToDelete.push(coreWorkflowId);-- const coreVersion = await readCoreVersionRow(coreWorkflowVersionId);- const coreWorkflow = await readCoreWorkflowRow(coreWorkflowId);-- await global.testDataSource.query(- `DELETE FROM "${TEST_WORKSPACE_SCHEMA}"."workflowVersion" WHERE id = $1`,- [coreVersion.workspaceWorkflowVersionId],- );- await global.testDataSource.query(- `DELETE FROM "${TEST_WORKSPACE_SCHEMA}"."workflow" WHERE id = $1`,- [coreWorkflow.workspaceWorkflowId],- );- });-- it('should still return the definition from core', async () => {- const current = await callWorkflowTool<{- success: boolean;- workflowVersion: { coreWorkflowVersionId: string };- }>('get_workflow_current_version', { coreWorkflowId });-- expect(current.success).toBe(true);- expect(current.workflowVersion.coreWorkflowVersionId).toBe(- coreWorkflowVersionId,- );- });-- it('should still list the workflow', async () => {- const listed = await callWorkflowTool<{- workflows: { coreWorkflowId: string }[];- }>('list_workflows', { limit: 100 });-- expect(- listed.workflows.some(- (workflow) => workflow.coreWorkflowId === coreWorkflowId,- ),- ).toBe(true);- });- });-describe('deletion', () => {it('should report a missing core workflow instead of reporting a deletion', async () => {const result = await callWorkflowTool<{diff --git a/packages/twenty-server/test/integration/email-tool/suites/outbound-email-body-formats.integration-spec.ts b/packages/twenty-server/test/integration/email-tool/suites/outbound-email-body-formats.integration-spec.tsindex e4ffc39df10..7d30b399111 100644--- a/packages/twenty-server/test/integration/email-tool/suites/outbound-email-body-formats.integration-spec.ts+++ b/packages/twenty-server/test/integration/email-tool/suites/outbound-email-body-formats.integration-spec.ts@@ -19,6 +19,10 @@ import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/geimport { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';+import {+ deleteLegacyWorkspaceWorkflowRecords,+ linkCoreWorkflowToLegacyWorkspaceIds,+} from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';import {runWorkflowActionStep,type WorkflowActionStepRun,@@ -92,10 +96,6 @@ const storeBodyAsBeforeTheUpgrade = async (`UPDATE core."workflowVersion" SET ${replaceEmailStepBody} WHERE "id" = $2`,[legacyBody, coreWorkflowVersionId],);- await global.testDataSource.query(- `UPDATE "${WORKSPACE_SCHEMA}"."workflowVersion" SET steps = (SELECT steps FROM core."workflowVersion" WHERE id = $1) WHERE "coreWorkflowVersionId" = $1`,- [coreWorkflowVersionId],- );};describe('Outbound email body formats (integration)', () => {@@ -394,6 +394,28 @@ describe('Outbound email body formats (integration)', () => {});describe('upgrade command', () => {+ const legacyWorkspaceWorkflowIds: string[] = [];++ const linkLegacyWorkspaceCopy = async (coreWorkflowVersionId: string) => {+ const [{ coreWorkflowId }] = await global.testDataSource.query(+ `SELECT "coreWorkflowId" FROM core."workflowVersion" WHERE id = $1`,+ [coreWorkflowVersionId],+ );+ const { workspaceWorkflowId } =+ await linkCoreWorkflowToLegacyWorkspaceIds({+ coreWorkflowId,+ withWorkspaceRecords: true,+ });++ legacyWorkspaceWorkflowIds.push(workspaceWorkflowId);+ };++ afterAll(async () => {+ for (const workspaceWorkflowId of legacyWorkspaceWorkflowIds) {+ await deleteLegacyWorkspaceWorkflowRecords({ workspaceWorkflowId });+ }+ });+const runUpgradeCommand = (dryRun: boolean) =>getAppProviderByClassName<WorkspaceOrmManager>('WorkspaceOrmManager',@@ -413,6 +435,8 @@ describe('Outbound email body formats (integration)', () => {const convertStoredBodyBeforeRun =(legacyBody: string) => async (coreWorkflowVersionId: string) => {+ await linkLegacyWorkspaceCopy(coreWorkflowVersionId);+expect(await readStoredBodies(coreWorkflowVersionId)).toEqual({workspaceBody: legacyBody,coreBody: legacyBody,@@ -461,6 +485,7 @@ describe('Outbound email body formats (integration)', () => {await runSendEmailWorkflow({body: '<p>Hello</p>',beforeRun: async (coreWorkflowVersionId) => {+ await linkLegacyWorkspaceCopy(coreWorkflowVersionId);await global.testDataSource.query(`UPDATE core."workflowVersion"SET steps = jsonb_set(steps, '{0,name}', '"Renamed in core only"')diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-application-auth.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-application-auth.integration-spec.tsindex 8852673e559..6e2ece53f42 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-application-auth.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-application-auth.integration-spec.ts@@ -14,8 +14,6 @@ import {SEED_YCOMBINATOR_WORKSPACE_ID,} from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';-const APPLE_WORKSPACE_SCHEMA = 'workspace_1wgvd1injqtife6y4rvfbu3h5';-const baseUrl = `http://localhost:${APP_PORT}`;type InstalledTestApplication = {@@ -113,11 +111,19 @@ const installApplicationWithoutUser = async ({};};+const findCoreWorkflowCreator = async (coreWorkflowId: string) => {+ const [coreWorkflow] = await global.testDataSource.query(+ `SELECT "createdByUserWorkspaceId" FROM core."workflow" WHERE id = $1`,+ [coreWorkflowId],+ );++ return coreWorkflow.createdByUserWorkspaceId as string | null;+};+const CREATE_CORE_WORKFLOW = `mutation CreateCoreWorkflow($input: CreateCoreWorkflowInput!) {createCoreWorkflow(input: $input) {id- workspaceWorkflowId}}`;@@ -279,19 +285,11 @@ describe('core workflow API with application credentials (integration)', () => {expect(createResponse.body.errors).toBeUndefined();- const { id: coreWorkflowId, workspaceWorkflowId } =- createResponse.body.data.createCoreWorkflow;+ const { id: coreWorkflowId } = createResponse.body.data.createCoreWorkflow;coreWorkflowIdsToDelete.push(coreWorkflowId);- const [mirror] = await global.testDataSource.query(- `SELECT "createdBySource", "createdByWorkspaceMemberId"- FROM "${APPLE_WORKSPACE_SCHEMA}"."workflow" WHERE id = $1`,- [workspaceWorkflowId],- );-- expect(mirror.createdBySource).toBe('APPLICATION');- expect(mirror.createdByWorkspaceMemberId).toBeNull();+ expect(await findCoreWorkflowCreator(coreWorkflowId)).toBeNull();});it('should attribute the workflow to the workspace member when a user creates it', async () => {@@ -303,19 +301,11 @@ describe('core workflow API with application credentials (integration)', () => {expect(createResponse.body.errors).toBeUndefined();- const { id: coreWorkflowId, workspaceWorkflowId } =- createResponse.body.data.createCoreWorkflow;+ const { id: coreWorkflowId } = createResponse.body.data.createCoreWorkflow;coreWorkflowIdsToDelete.push(coreWorkflowId);- const [mirror] = await global.testDataSource.query(- `SELECT "createdBySource", "createdByWorkspaceMemberId", "createdByName"- FROM "${APPLE_WORKSPACE_SCHEMA}"."workflow" WHERE id = $1`,- [workspaceWorkflowId],- );-- expect(mirror.createdBySource).toBe('MANUAL');- expect(mirror.createdByWorkspaceMemberId).not.toBeNull();+ expect(await findCoreWorkflowCreator(coreWorkflowId)).not.toBeNull();});it('should keep the application role when a user acts through the application', async () => {@@ -334,19 +324,11 @@ describe('core workflow API with application credentials (integration)', () => {expect(createResponse.body.errors).toBeUndefined();- const { id: coreWorkflowId, workspaceWorkflowId } =- createResponse.body.data.createCoreWorkflow;+ const { id: coreWorkflowId } = createResponse.body.data.createCoreWorkflow;coreWorkflowIdsToDelete.push(coreWorkflowId);- const [mirror] = await global.testDataSource.query(- `SELECT "createdBySource", "createdByWorkspaceMemberId"- FROM "${APPLE_WORKSPACE_SCHEMA}"."workflow" WHERE id = $1`,- [workspaceWorkflowId],- );-- expect(mirror.createdBySource).toBe('MANUAL');- expect(mirror.createdByWorkspaceMemberId).not.toBeNull();+ expect(await findCoreWorkflowCreator(coreWorkflowId)).not.toBeNull();});it('should refuse an API key, which is neither a user nor an application', async () => {diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.tsindex 240a0a7d6b8..7114db0303c 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts@@ -33,6 +33,8 @@ import {coreWorkflowGraphqlRequest,createCoreWorkflow,deleteCoreWorkflows,+ deleteLegacyWorkspaceWorkflowRecords,+ linkCoreWorkflowToLegacyWorkspaceIds,runCoreWorkflowVersion,updateCoreWorkflowVersionTrigger,} from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';@@ -144,13 +146,14 @@ describe('core workflow execution and queue compatibility (e2e)', () => {coreWorkflowId = coreWorkflow.coreWorkflowId;coreWorkflowVersionId = coreWorkflow.coreWorkflowVersionId;- workflowId = coreWorkflow.workspaceWorkflowId;- const [version] = await global.testDataSource.query(- `SELECT "workspaceWorkflowVersionId" FROM core."workflowVersion" WHERE id = $1`,- [coreWorkflowVersionId],- );- workflowVersionId = version.workspaceWorkflowVersionId;+ const legacyIds = await linkCoreWorkflowToLegacyWorkspaceIds({+ coreWorkflowId,+ withWorkspaceRecords: true,+ });++ workflowId = legacyIds.workspaceWorkflowId;+ workflowVersionId = legacyIds.workspaceWorkflowVersionIds[0];await global.testDataSource.query(`UPDATE core."workflowVersion" SET triggers = $2, steps = $3, status = 'ACTIVE' WHERE id = $1`,[@@ -258,6 +261,9 @@ describe('core workflow execution and queue compatibility (e2e)', () => {await deleteCoreWorkflows({coreWorkflowIds: [fixture.coreWorkflowId],});+ await deleteLegacyWorkspaceWorkflowRecords({+ workspaceWorkflowId: fixture.workflowId,+ });}await global.testDataSource.query('DELETE FROM core."workflowVersion" WHERE "coreWorkflowId" = $1',@@ -2263,62 +2269,6 @@ describe('core workflow execution and queue compatibility (e2e)', () => {expect(core.steps[0].position).toEqual({ x: 321, y: 654 });});- it('allows reconciliation to acquire core locks during a blocked rename', async () => {- const fixture = await createFixture();-- const transaction = global.testDataSource.createQueryRunner();-- await transaction.connect();- await transaction.startTransaction();- await transaction.query(- `SELECT id FROM "${schema}"."workflow" WHERE id = $1 FOR UPDATE`,- [fixture.workflowId],- );- const [{ pid }] = await transaction.query('SELECT pg_backend_pid() AS pid');- const mutation = workflowGraphqlRequest(- 'mutation Update($input: UpdateCoreWorkflowInput!) { updateCoreWorkflow(input: $input) { id name } }',- {- input: {- coreWorkflowId: fixture.coreWorkflowId,- name: 'Concurrent rename',- },- },- ).then((response) => response);-- try {- let blocked = false;-- for (let attempt = 0; attempt < 100; attempt++) {- const [activity] = await global.testDataSource.query(- `SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid))) AS blocked`,- [pid],- );-- if (activity.blocked) {- blocked = true;- break;- }-- await new Promise((resolve) => setTimeout(resolve, 20));- }-- expect(blocked).toBe(true);- await transaction.query(- 'SELECT id FROM core.workflow WHERE id = $1 FOR UPDATE NOWAIT',- [fixture.coreWorkflowId],- );- await transaction.commitTransaction();- expect((await mutation).body.errors).toBeUndefined();- } finally {- if (transaction.isTransactionActive) {- await transaction.rollbackTransaction();- }-- await transaction.release();- await mutation;- }- });-it('fires a mirrorless database-event workflow from a real record creation', async () => {const fixture = await createFixture({mirrorless: true,diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-id-native-queries.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-id-native-queries.integration-spec.tsindex eb7653afaae..690ea66cc73 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-id-native-queries.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-id-native-queries.integration-spec.ts@@ -1,4 +1,7 @@-import { deleteCoreWorkflows } from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';+import {+ deleteCoreWorkflows,+ linkCoreWorkflowToLegacyWorkspaceIds,+} from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';import { workflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/workflow-graphql-request.util';const CORE_WORKFLOW_VERSIONS_BY_CORE_WORKFLOW_ID = `@@ -47,7 +50,6 @@ describe('core workflow id native queries (e2e)', () => {mutation {createCoreWorkflow(input: { name: "Core Id Native Queries" }) {id- workspaceWorkflowId}}`);@@ -55,15 +57,16 @@ describe('core workflow id native queries (e2e)', () => {expect(createResponse.body.errors).toBeUndefined();coreWorkflowId = createResponse.body.data.createCoreWorkflow.id;- workspaceWorkflowId =- createResponse.body.data.createCoreWorkflow.workspaceWorkflowId;+ ({ workspaceWorkflowId } = await linkCoreWorkflowToLegacyWorkspaceIds({+ coreWorkflowId,+ }));});afterAll(async () => {await deleteCoreWorkflows({ coreWorkflowIds: [coreWorkflowId] });});- it('lists the versions by core workflow id, mirror ids included', async () => {+ it('lists the versions by core workflow id, legacy workspace ids included', async () => {const response = await workflowGraphqlRequest(CORE_WORKFLOW_VERSIONS_BY_CORE_WORKFLOW_ID,{ coreWorkflowId },diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-mutations.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-mutations.integration-spec.tsindex daf2c678e3f..7d16340b958 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-mutations.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-mutations.integration-spec.ts@@ -2,8 +2,6 @@ import request from 'supertest';import { deleteCoreWorkflows } from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';import { isDefined } from 'twenty-shared/utils';-const TEST_SCHEMA_NAME = 'workspace_1wgvd1injqtife6y4rvfbu3h5';-const client = request(`http://localhost:${APP_PORT}`);const graphql = (query: string, variables?: object) =>@@ -39,7 +37,6 @@ type CoreWorkflow = {describe('coreWorkflow mutations (e2e)', () => {let coreWorkflowId: string;- let workspaceWorkflowId: string;const findListedCoreWorkflowById = async (id: string,@@ -61,7 +58,7 @@ describe('coreWorkflow mutations (e2e)', () => {await deleteCoreWorkflows({ coreWorkflowIds: [coreWorkflowId] });});- it('should create a workflow listed synchronously with a draft version', async () => {+ it('should create a workflow listed synchronously with a draft version and no workspace record', async () => {const createResponse = await graphql(`mutation {createCoreWorkflow(input: { name: "Core Created Workflow" }) {@@ -79,55 +76,28 @@ describe('coreWorkflow mutations (e2e)', () => {expect(createdCoreWorkflow.name).toBe('Core Created Workflow');expect(createdCoreWorkflow.statuses).toEqual(['DRAFT']);- expect(createdCoreWorkflow.workspaceWorkflowId).toBeDefined();+ expect(createdCoreWorkflow.workspaceWorkflowId).toBeNull();coreWorkflowId = createdCoreWorkflow.id;- workspaceWorkflowId = createdCoreWorkflow.workspaceWorkflowId;const listedCoreWorkflow = await findListedCoreWorkflowById(coreWorkflowId);expect(listedCoreWorkflow).toBeDefined();expect(listedCoreWorkflow?.statuses).toEqual(['DRAFT']);- expect(listedCoreWorkflow?.workspaceWorkflowId).toBe(workspaceWorkflowId);-- const storedCoreWorkflowRows = await global.testDataSource.query(- `SELECT "workspaceWorkflowId" FROM core."workflow" WHERE "id" = $1`,+ expect(listedCoreWorkflow?.workspaceWorkflowId).toBeNull();++ const coreVersionRows: {+ status: string;+ workflowId: string | null;+ workspaceWorkflowVersionId: string | null;+ }[] = await global.testDataSource.query(+ `SELECT status, "workflowId", "workspaceWorkflowVersionId" FROM core."workflowVersion" WHERE "coreWorkflowId" = $1`,[coreWorkflowId],);- expect(storedCoreWorkflowRows[0]?.workspaceWorkflowId).toBe(- workspaceWorkflowId,- );-- const workspaceWorkflowResponse = await graphql(- `- query GetWorkflow($id: UUID!) {- workflow(filter: { id: { eq: $id } }) {- id- name- versions {- edges {- node {- id- name- status- }- }- }- }- }- `,- { id: workspaceWorkflowId },- );-- expect(workspaceWorkflowResponse.body.errors).toBeUndefined();-- const workspaceWorkflow = workspaceWorkflowResponse.body.data.workflow;-- expect(workspaceWorkflow.name).toBe('Core Created Workflow');- expect(workspaceWorkflow.versions.edges).toHaveLength(1);- expect(workspaceWorkflow.versions.edges[0].node.name).toBe('v1');- expect(workspaceWorkflow.versions.edges[0].node.status).toBe('DRAFT');+ expect(coreVersionRows).toEqual([+ { status: 'DRAFT', workflowId: null, workspaceWorkflowVersionId: null },+ ]);});it('should delete workflows and unlist them synchronously', async () => {@@ -145,28 +115,10 @@ describe('coreWorkflow mutations (e2e)', () => {expect(deleteResponse.body.errors).toBeUndefined();expect(deleteResponse.body.data.deleteCoreWorkflows).toEqual([- { id: coreWorkflowId, workspaceWorkflowId },+ { id: coreWorkflowId, workspaceWorkflowId: null },]);expect(await findListedCoreWorkflowById(coreWorkflowId)).toBeUndefined();-- const softDeletedWorkflowResponse = await graphql(- `- query DeletedWorkflow($id: UUID!) {- workflow(- filter: { id: { eq: $id }, not: { deletedAt: { is: "NULL" } } }- ) {- id- }- }- `,- { id: workspaceWorkflowId },- );-- expect(softDeletedWorkflowResponse.body.errors).toBeUndefined();- expect(softDeletedWorkflowResponse.body.data.workflow?.id).toBe(- workspaceWorkflowId,- );});it('should report nothing when deleting the same workflows again', async () => {@@ -212,65 +164,6 @@ describe('coreWorkflow mutations (e2e)', () => {await deleteCoreWorkflows({ coreWorkflowIds: [createdCoreWorkflow.id] });});- it('should finish the cleanup on a retry after the core row is gone', async () => {- const createResponse = await graphql(`- mutation {- createCoreWorkflow(input: { name: "Core Retry Delete" }) {- id- workspaceWorkflowId- }- }- `);-- expect(createResponse.body.errors).toBeUndefined();-- const retryCoreWorkflowId = createResponse.body.data.createCoreWorkflow.id;- const retryWorkspaceWorkflowId =- createResponse.body.data.createCoreWorkflow.workspaceWorkflowId;-- const deleteMutation = `- mutation DeleteCoreWorkflows($input: DeleteCoreWorkflowsInput!) {- deleteCoreWorkflows(input: $input) {- id- workspaceWorkflowId- }- }- `;-- const firstDeleteResponse = await graphql(deleteMutation, {- input: { coreWorkflowIds: [retryCoreWorkflowId] },- });-- expect(firstDeleteResponse.body.errors).toBeUndefined();- expect(firstDeleteResponse.body.data.deleteCoreWorkflows).toEqual([- {- id: retryCoreWorkflowId,- workspaceWorkflowId: retryWorkspaceWorkflowId,- },- ]);-- await global.testDataSource.query(- `UPDATE "${TEST_SCHEMA_NAME}"."workflowVersion" SET "deletedAt" = NULL WHERE "workflowId" = $1`,- [retryWorkspaceWorkflowId],- );-- const retryDeleteResponse = await graphql(deleteMutation, {- input: { coreWorkflowIds: [retryCoreWorkflowId] },- });-- expect(retryDeleteResponse.body.errors).toBeUndefined();- expect(retryDeleteResponse.body.data.deleteCoreWorkflows).toEqual([]);-- const workflowVersionRows: { deletedAt: Date | null }[] =- await global.testDataSource.query(- `SELECT "deletedAt" FROM "${TEST_SCHEMA_NAME}"."workflowVersion" WHERE "workflowId" = $1`,- [retryWorkspaceWorkflowId],- );-- expect(workflowVersionRows).toHaveLength(1);- expect(workflowVersionRows[0].deletedAt).not.toBeNull();- });-it('should delete nothing for unknown core workflow ids', async () => {const deleteResponse = await graphql(`diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-read.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-read.integration-spec.tsindex 2fac1bea414..73da605f22c 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-read.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-read.integration-spec.ts@@ -3,6 +3,7 @@ import { isDefined } from 'twenty-shared/utils';import {createCoreWorkflow,deleteCoreWorkflows,+ linkCoreWorkflowToLegacyWorkspaceIds,} from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';import { pollWorkflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/poll-workflow-graphql-request.util';import { workflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/workflow-graphql-request.util';@@ -91,7 +92,9 @@ describe('coreWorkflow (e2e)', () => {});coreWorkflowId = createdCoreWorkflow.coreWorkflowId;- workspaceWorkflowId = createdCoreWorkflow.workspaceWorkflowId;+ ({ workspaceWorkflowId } = await linkCoreWorkflowToLegacyWorkspaceIds({+ coreWorkflowId,+ }));});afterAll(async () => {diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.tsindex 50ab3a178c0..0553b6b67db 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts@@ -20,6 +20,7 @@ import {createCoreWorkflowVersionStep,deleteCoreWorkflows,findCoreWorkflowVersion,+ linkCoreWorkflowToLegacyWorkspaceIds,runCoreWorkflowVersion,updateCoreWorkflowVersionTrigger,} from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';@@ -146,9 +147,14 @@ const listCoreWorkflowIds = async ();};-const createWorkflowWithMirrorIds = async (name: string) => {- const { coreWorkflowId, coreWorkflowVersionId, workspaceWorkflowId } =- await createCoreWorkflow({ name });+const createWorkflowWithLegacyIds = async (name: string) => {+ const { coreWorkflowId, coreWorkflowVersionId } = await createCoreWorkflow({+ name,+ });++ const { workspaceWorkflowId } = await linkCoreWorkflowToLegacyWorkspaceIds({+ coreWorkflowId,+ });const { workspaceWorkflowVersionId } = await findCoreWorkflowVersion({coreWorkflowVersionId,@@ -157,15 +163,12 @@ const createWorkflowWithMirrorIds = async (name: string) => {return {coreWorkflowId,coreWorkflowVersionId,- workspaceWorkflowId: workspaceWorkflowId!,+ workspaceWorkflowId,workspaceWorkflowVersionId: workspaceWorkflowVersionId!,};};-const createActiveManualWorkflow = async (name: string) => {- const createdWorkflow = await createWorkflowWithMirrorIds(name);- const { coreWorkflowVersionId } = createdWorkflow;-+const activateManualTrigger = async (coreWorkflowVersionId: string) => {await updateCoreWorkflowVersionTrigger({coreWorkflowVersionId,trigger: {@@ -183,6 +186,12 @@ const createActiveManualWorkflow = async (name: string) => {});await activateCoreWorkflowVersion({ coreWorkflowVersionId });+};++const createActiveManualWorkflow = async (name: string) => {+ const createdWorkflow = await createCoreWorkflow({ name });++ await activateManualTrigger(createdWorkflow.coreWorkflowVersionId);return createdWorkflow;};@@ -271,7 +280,7 @@ describe('core workflow visibility (e2e)', () => {coreWorkflowVersionId,workspaceWorkflowId,workspaceWorkflowVersionId,- } = await createWorkflowWithMirrorIds('Private Workflow Access'));+ } = await createWorkflowWithLegacyIds('Private Workflow Access'));});afterAll(async () => {@@ -569,10 +578,15 @@ describe('core workflow visibility (e2e)', () => {};beforeAll(async () => {- ({- coreWorkflowId: manualCoreWorkflowId,- workspaceWorkflowVersionId: manualWorkspaceWorkflowVersionId,- } = await createActiveManualWorkflow('Manual Trigger Workflow'));+ const createdWorkflow = await createWorkflowWithLegacyIds(+ 'Manual Trigger Workflow',+ );++ await activateManualTrigger(createdWorkflow.coreWorkflowVersionId);++ manualCoreWorkflowId = createdWorkflow.coreWorkflowId;+ manualWorkspaceWorkflowVersionId =+ createdWorkflow.workspaceWorkflowVersionId;});afterAll(async () => {diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/core-workflow.util.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/core-workflow.util.tsindex 62fe574507d..7e3b4f4d486 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/core-workflow.util.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/core-workflow.util.ts@@ -1,6 +1,11 @@+import { randomUUID } from 'node:crypto';+import request from 'supertest';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';+const client = request(`http://localhost:${APP_PORT}`);type CoreWorkflowStep = {@@ -93,6 +98,100 @@ export const createCoreWorkflow = async ({};};+export const linkCoreWorkflowToLegacyWorkspaceIds = async ({+ coreWorkflowId,+ withWorkspaceRecords = false,+}: {+ coreWorkflowId: string;+ withWorkspaceRecords?: boolean;+}): Promise<{+ workspaceWorkflowId: string;+ workspaceWorkflowVersionIds: string[];+}> => {+ const workspaceSchema = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);+ const workspaceWorkflowId = randomUUID();++ await global.testDataSource.query(+ `UPDATE core."workflow" SET "workspaceWorkflowId" = $2 WHERE id = $1`,+ [coreWorkflowId, workspaceWorkflowId],+ );++ if (withWorkspaceRecords) {+ await global.testDataSource.query(+ `INSERT INTO "${workspaceSchema}"."workflow" (id, name, "coreWorkflowId")+ SELECT $1, name, id FROM core."workflow" WHERE id = $2`,+ [workspaceWorkflowId, coreWorkflowId],+ );+ }++ const coreVersions: {+ id: string;+ status: string;+ triggers: object[] | null;+ steps: object[] | null;+ }[] = await global.testDataSource.query(+ `SELECT id, status, triggers, steps FROM core."workflowVersion" WHERE "coreWorkflowId" = $1 ORDER BY "createdAt"`,+ [coreWorkflowId],+ );++ const workspaceWorkflowVersionIds: string[] = [];++ for (const coreVersion of coreVersions) {+ const workspaceWorkflowVersionId = randomUUID();++ await global.testDataSource.query(+ `UPDATE core."workflowVersion" SET "workflowId" = $2, "workspaceWorkflowVersionId" = $3 WHERE id = $1`,+ [coreVersion.id, workspaceWorkflowId, workspaceWorkflowVersionId],+ );++ if (withWorkspaceRecords) {+ await global.testDataSource.query(+ `INSERT INTO "${workspaceSchema}"."workflowVersion" (id, "workflowId", name, status, trigger, steps, "coreWorkflowVersionId")+ VALUES ($1, $2, $3, $4, $5, $6, $7)`,+ [+ workspaceWorkflowVersionId,+ workspaceWorkflowId,+ `v${workspaceWorkflowVersionIds.length + 1}`,+ coreVersion.status,+ isDefined(coreVersion.triggers?.[0])+ ? JSON.stringify(coreVersion.triggers[0])+ : null,+ isDefined(coreVersion.steps)+ ? JSON.stringify(coreVersion.steps)+ : null,+ coreVersion.id,+ ],+ );+ }++ workspaceWorkflowVersionIds.push(workspaceWorkflowVersionId);+ }++ await global.workflowTestServices.workspaceCache.invalidateAndRecompute(+ SEED_APPLE_WORKSPACE_ID,+ ['flatWorkflowMaps', 'flatWorkflowVersionMaps'],+ );++ return { workspaceWorkflowId, workspaceWorkflowVersionIds };+};++export const deleteLegacyWorkspaceWorkflowRecords = async ({+ workspaceWorkflowId,+}: {+ workspaceWorkflowId: string;+}): Promise<void> => {+ const workspaceSchema = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);++ await global.testDataSource.query(+ `DELETE FROM "${workspaceSchema}"."workflowVersion" WHERE "workflowId" = $1`,+ [workspaceWorkflowId],+ );+ await global.testDataSource.query(+ `DELETE FROM "${workspaceSchema}"."workflow" WHERE id = $1`,+ [workspaceWorkflowId],+ );+};+export const findCoreWorkflowVersions = async ({coreWorkflowId,token,diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-deletion-cleanup.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-deletion-cleanup.integration-spec.tsindex d2990c595c8..750981488bd 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-deletion-cleanup.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-deletion-cleanup.integration-spec.ts@@ -19,7 +19,6 @@ import {createCoreWorkflow,createCoreWorkflowVersionStep,deleteCoreWorkflows,- findCoreWorkflowVersion,updateCoreWorkflowVersionStep,updateCoreWorkflowVersionTrigger,} from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';@@ -103,7 +102,6 @@ describe('workflow deletion cleanup', () => {describe('deleting a workspace workflow', () => {type WorkspaceWorkflow = {- workflowVersionId: string;coreWorkflowId: string;coreWorkflowVersionId: string;};@@ -135,12 +133,7 @@ describe('workflow deletion cleanup', () => {},});- const { workspaceWorkflowVersionId } = await findCoreWorkflowVersion({- coreWorkflowVersionId,- });-return {- workflowVersionId: workspaceWorkflowVersionId!,coreWorkflowId,coreWorkflowVersionId,};@@ -332,11 +325,8 @@ describe('workflow deletion cleanup', () => {it('deletes the definition, triggers, CODE functions and runs of the deleted workflow only, before the deletion returns', async () => {expect(await countRows(- `core."commandMenuItem" WHERE "coreWorkflowVersionId" = $1 OR "workflowVersionId" = $2`,- [- deletedWorkflow.coreWorkflowVersionId,- deletedWorkflow.workflowVersionId,- ],+ `core."commandMenuItem" WHERE "coreWorkflowVersionId" = $1`,+ [deletedWorkflow.coreWorkflowVersionId],),).toBe(1);@@ -366,11 +356,8 @@ describe('workflow deletion cleanup', () => {).toBe(0);expect(await countRows(- `core."commandMenuItem" WHERE "coreWorkflowVersionId" = $1 OR "workflowVersionId" = $2`,- [- deletedWorkflow.coreWorkflowVersionId,- deletedWorkflow.workflowVersionId,- ],+ `core."commandMenuItem" WHERE "coreWorkflowVersionId" = $1`,+ [deletedWorkflow.coreWorkflowVersionId],),).toBe(0);expect(diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-resolver.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-resolver.integration-spec.tsindex bf4ad0300a9..dffe8e7410b 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-resolver.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-resolver.integration-spec.ts@@ -6,7 +6,8 @@ import {createCoreWorkflowVersionStep,deactivateCoreWorkflowVersion,deleteCoreWorkflows,- findCoreWorkflowVersion,+ deleteLegacyWorkspaceWorkflowRecords,+ linkCoreWorkflowToLegacyWorkspaceIds,updateCoreWorkflowVersionTrigger,} from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';import { findCommandMenuItems } from 'test/integration/metadata/suites/command-menu-item/utils/find-command-menu-items.util';@@ -24,25 +25,21 @@ describe('workflowResolver', () => {const createdWorkflow = await createCoreWorkflow({name: 'Records API write rejection',});- const { workspaceWorkflowVersionId: draftWorkspaceWorkflowVersionId } =- await findCoreWorkflowVersion({- coreWorkflowVersionId: createdWorkflow.coreWorkflowVersionId,- });-- if (- createdWorkflow.workspaceWorkflowId === null ||- draftWorkspaceWorkflowVersionId === null- ) {- throw new Error('Expected the core workflow to have a workspace mirror');- }coreWorkflowId = createdWorkflow.coreWorkflowId;- workspaceWorkflowId = createdWorkflow.workspaceWorkflowId;- workspaceWorkflowVersionId = draftWorkspaceWorkflowVersionId;++ const legacyIds = await linkCoreWorkflowToLegacyWorkspaceIds({+ coreWorkflowId,+ withWorkspaceRecords: true,+ });++ workspaceWorkflowId = legacyIds.workspaceWorkflowId;+ workspaceWorkflowVersionId = legacyIds.workspaceWorkflowVersionIds[0];});afterAll(async () => {await deleteCoreWorkflows({ coreWorkflowIds: [coreWorkflowId] });+ await deleteLegacyWorkspaceWorkflowRecords({ workspaceWorkflowId });});it.each([diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-version-malformed-validation.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-version-malformed-validation.integration-spec.tsindex 4e4d22e5439..1f300f49546 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-version-malformed-validation.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-version-malformed-validation.integration-spec.ts@@ -3,7 +3,8 @@ import {createCoreWorkflow,createCoreWorkflowVersionStep,deleteCoreWorkflows,- findCoreWorkflowVersion,+ deleteLegacyWorkspaceWorkflowRecords,+ linkCoreWorkflowToLegacyWorkspaceIds,updateCoreWorkflowVersionTrigger,} from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';@@ -34,7 +35,8 @@ const updateStepResponse = (describe('Workflow version malformed validation (e2e)', () => {let coreWorkflowId: string;let coreWorkflowVersionId: string;- let workspaceWorkflowVersionId: string | null;+ let workspaceWorkflowId: string;+ let workspaceWorkflowVersionId: string;let createRecordStep: {id: string;settings: { input: Record<string, unknown> };@@ -74,15 +76,18 @@ describe('Workflow version malformed validation (e2e)', () => {position: { x: 400, y: 0 },});- const coreWorkflowVersion = await findCoreWorkflowVersion({- coreWorkflowVersionId,+ const legacyIds = await linkCoreWorkflowToLegacyWorkspaceIds({+ coreWorkflowId,+ withWorkspaceRecords: true,});- workspaceWorkflowVersionId = coreWorkflowVersion.workspaceWorkflowVersionId;+ workspaceWorkflowId = legacyIds.workspaceWorkflowId;+ workspaceWorkflowVersionId = legacyIds.workspaceWorkflowVersionIds[0];});afterAll(async () => {await deleteCoreWorkflows({ coreWorkflowIds: [coreWorkflowId] });+ await deleteLegacyWorkspaceWorkflowRecords({ workspaceWorkflowId });});const sendEmailStepWithBody = (body: string) => ({@@ -183,7 +188,7 @@ describe('Workflow version malformed validation (e2e)', () => {const operation = updateOneOperationFactory({objectMetadataSingularName: 'workflowVersion',gqlFields: 'id',- recordId: workspaceWorkflowVersionId!,+ recordId: workspaceWorkflowVersionId,data: { steps: [] },});