Skip to content

The open alternative to Salesforce, designed for AI.

Pull and apply workflows built in the workflow builder (#29050)

Félix Malfaita4162f8b99a1
diff --git a/packages/twenty-cli/docs/commands.md b/packages/twenty-cli/docs/commands.md
index f3da5b3d2da..b3f3c484864 100644
--- a/packages/twenty-cli/docs/commands.md
+++ b/packages/twenty-cli/docs/commands.md
@@ -435,7 +435,7 @@ failures restore the previous files and baseline.
Failures in reconciliation report `error.details.outcome`: `unchanged` after an acknowledged refusal, cancellation before writing or successful rollback; `unknown` if a worker stops without acknowledging completion or rollback fails; `pulled` if writes and baseline completed but temporary-file cleanup failed. An interrupted worker can leave files partially written; inspect the changes and retained `.twenty/cli/pull-backup-*` files before retrying. A failed rollback also reports `backupDirectory`. Ctrl+C exits 130 unless the worker acknowledges a completed commit, in which case pull returns its result.
-The current export contains metadata and translations, not application source assets or dependency files. Workflows are written as `defineWorkflow` files in `src/workflows`; a workflow changed in the workflow builder, or one using steps or references an application cannot declare, is reported as a coverage gap and its local file is kept. Skills and agents are written as `defineSkill` and `defineAgent` files in `src/skills` and `src/agents`; one the server cannot reproduce from a definition, such as an agent on more than one role, is reported as a coverage gap and its local file is kept. Logic-function/front-component code and unsupported metadata are not regenerated. An export with nonempty `files` is refused before writing. Package files, dependency pins and the installed generated client are left alone; pull never installs dependencies. Each export response is limited to 16 MiB. See the [pull implementation](../src/app/pull/README.md) for reconciliation and compatibility details.
+The current export contains metadata and translations, not application source assets or dependency files. Workflows are written as `defineWorkflow` files in `src/workflows`; a workflow changed in the workflow builder, or one using steps or references an application cannot declare, is reported as a coverage gap and its local file is kept. The workspace Custom application is published from the builder too, so its workflows are written from their active version, and apply publishes a changed definition as a new version. Skills and agents are written as `defineSkill` and `defineAgent` files in `src/skills` and `src/agents`; one the server cannot reproduce from a definition, such as an agent on more than one role, is reported as a coverage gap and its local file is kept. Logic-function/front-component code and unsupported metadata are not regenerated. An export with nonempty `files` is refused before writing. Package files, dependency pins and the installed generated client are left alone; pull never installs dependencies. Each export response is limited to 16 MiB. See the [pull implementation](../src/app/pull/README.md) for reconciliation and compatibility details.
## Install a registered app
diff --git a/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx b/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx
index 5dcf96f3377..397cb347681 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx
@@ -114,4 +114,11 @@ Their inputs match the steps of the [workflow builder](/user-guide/workflows/cap
- Installing a new version of the app updates the workflow in place.
- Users can't edit an installed workflow. To customize one, they duplicate it: the copy is theirs to edit.
+## Workflows of the workspace Custom application
+
+The workspace Custom application owns the workflows built in the workflow builder, and code is as authoritative for them as the builder:
+- `twenty app pull` writes each one from its active version, the one the builder last published. A workflow whose active version uses settings a `defineWorkflow()` file can't express, such as a Code step or a trigger the builder renamed, is reported and left in place.
+- `twenty app apply` publishes like the builder. A workflow whose definition matches its active version is left alone. Otherwise the active version is archived and the definition becomes a new active version, so past runs keep the version they ran.
+- Users keep editing these workflows in the builder, and the next pull brings their changes back.
+
<PageBanner illustration="card-page-workflows" />
diff --git a/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx b/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx
index 6b5452c61f2..515147d7eb2 100644
--- a/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx
+++ b/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx
@@ -131,7 +131,7 @@ Pull needs an existing project — scaffold one with `twenty app init` first, th
- tabs your app added to page layouts it does not own, as standalone `definePageLayoutTab()` files;
- navigation menu items, as `defineNavigationMenuItem()` files, folders included;
- widgets your app added to tabs it does not own, as standalone `definePageLayoutWidget()` files;
-- workflows, as `defineWorkflow()` files, when their stored version is the one the last sync wrote;
+- workflows, as `defineWorkflow()` files, when their stored version is the one the last sync wrote. For the workspace Custom application, it is the active version, whether a sync or the workflow builder published it, and apply publishes a changed definition as a new version, as described in [Workflows](/developers/extend/apps/logic/workflows#workflows-of-the-workspace-custom-application);
- skills, as `defineSkill()` files;
- agents, as `defineAgent()` files, with their triggers and the role your app binds them to;
- published translations, as `locales/<locale>.json` for the strings pull can read back from the pulled metadata and source, and `locales/compiled/<locale>.json` for the rest.
@@ -145,7 +145,7 @@ Each entity goes to the file that already defines it, so a second pull rewrites
- **Placed on a default or foreign view** — filters, filter groups, sorts, groups and field groups added to an engine default view, or to a view owned by another application, have no source form yet and are reported. View fields added there are written as standalone files, since the view's identifier is known.
- **Placed on a default or foreign page layout** — tabs and widgets added to an engine default page layout, or to one owned by another application, are written as standalone `definePageLayoutTab()` and `definePageLayoutWidget()` files, since the identifier they attach to is known.
- **Widgets the export cannot carry yet** — on any layout, including your own, a widget of the deprecated `VIEW` type, a widget showing one of your app's own front components or command menu items, or a widget without a position for its tab's layout mode is reported, and the layout or tab is written without it.
-- **Workflows the export cannot carry yet** — a workflow changed in the workflow builder since the last sync, one built in the workspace, a system or private workflow, one with a Code or chat message step, which application workflows don't support, or an email or calendar step, which export doesn't carry yet, and one calling another app's workflow action are reported and left in place. The workspace custom application is the exception for that last case: its workflows may call any app's actions, so they are pulled.
+- **Workflows the export cannot carry yet** — a workflow changed in the workflow builder since the last sync, a system or private workflow, one with a Code or chat message step, which application workflows don't support, or an email or calendar step, which export doesn't carry yet, and one calling another app's workflow action are reported and left in place. The workspace custom application is the exception for the first and last cases: the builder publishes its workflows too, and they may call any app's actions, so they are pulled. One of its workflows is reported instead when it has no active version, or when its active version uses settings a definition can't express.
- **Agents and skills the export cannot carry yet** — a deactivated skill, and an agent on more than one role or bound to a role pull does not write, are reported and left in place.
- **Workspace runtime state** — member and API-key role assignments, webhooks, per-user navigation and navigation items pinned to a record, all excluded by design.
- **Owned by another application** — reported, never pulled.
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 4003924b521..88a79c69ff2 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
@@ -245,8 +245,7 @@ export class ApplicationManifestMigrationService {
toAllUniversalFlatEntityMaps,
existingAllFlatEntityMaps,
idByUniversalIdentifierByMetadataName,
- // Its workflows run as workspace workflows, which may already call any app's actions
- canReferenceOtherApplicationsWorkflowActions:
+ isWorkspaceCustomApplication:
ownerFlatApplication.id === workspaceCustomFlatApplication?.id,
now,
});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-flat-workflow-to-workflow-manifest.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-flat-workflow-to-workflow-manifest.util.ts
index 5c8d16bdf28..7eccec47b84 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-flat-workflow-to-workflow-manifest.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-flat-workflow-to-workflow-manifest.util.ts
@@ -1,5 +1,4 @@
import { isNonEmptyString } from '@sniptt/guards';
-import isEqual from 'lodash.isequal';
import {
type WorkflowManifest,
type WorkflowStepManifest,
@@ -11,12 +10,10 @@ import { fromWorkflowActionToWorkflowStepManifest } from 'src/engine/core-module
import { fromWorkflowManifestToUniversalFlatWorkflowOrThrow } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util';
import { fromWorkflowTriggerToWorkflowTriggerManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-trigger-to-workflow-trigger-manifest.util';
import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
+import { isSameWorkflowVersionDefinition } from 'src/engine/core-modules/application/application-manifest/utils/is-same-workflow-version-definition.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 toJsonValue = (value: unknown): unknown =>
- JSON.parse(JSON.stringify(value ?? null));
-
const isReproducedBySyncOrThrow = ({
manifest,
flatWorkflow,
@@ -38,15 +35,12 @@ const isReproducedBySyncOrThrow = ({
...references,
}).flatUniversalWorkflowVersion;
- return isEqual(
- toJsonValue({
- triggers: reproducedVersion?.triggers,
- steps: reproducedVersion?.steps,
- }),
- toJsonValue({
- triggers: flatWorkflowVersion.triggers,
- steps: flatWorkflowVersion.steps,
- }),
+ return isSameWorkflowVersionDefinition(
+ {
+ triggers: reproducedVersion?.triggers ?? null,
+ steps: reproducedVersion?.steps ?? null,
+ },
+ flatWorkflowVersion,
);
};
@@ -54,10 +48,12 @@ export const fromFlatWorkflowToWorkflowManifest = ({
flatWorkflow,
flatWorkflowVersion,
references,
+ unreproducibleReason = WORKFLOW_CHANGED_IN_BUILDER_REASON,
}: {
flatWorkflow: FlatWorkflow;
flatWorkflowVersion: FlatWorkflowVersion;
references: WorkflowManifestReferences;
+ unreproducibleReason?: string;
}): { manifest: WorkflowManifest } | { reason: string } => {
const { triggers, steps } = flatWorkflowVersion;
const [trigger] = triggers ?? [];
@@ -114,7 +110,7 @@ export const fromFlatWorkflowToWorkflowManifest = ({
references,
})
) {
- return { reason: WORKFLOW_CHANGED_IN_BUILDER_REASON };
+ return { reason: unreproducibleReason };
}
} catch (error) {
return {
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
index 3b4f17838b3..8b3d9dc7bbf 100644
--- 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
@@ -4,6 +4,7 @@ import { fromWorkflowManifestToUniversalFlatCommandMenuItem } from 'src/engine/c
import { fromWorkflowStepManifestToActionOrThrow } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util';
import { fromWorkflowTriggerManifestToTriggerOrThrow } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-trigger-manifest-to-trigger-or-throw.util';
import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';
+import { isSameWorkflowVersionDefinition } from 'src/engine/core-modules/application/application-manifest/utils/is-same-workflow-version-definition.util';
import { msg } from '@lingui/core/macro';
import { isDefined, sortKeysDeeply } from 'twenty-shared/utils';
import {
@@ -22,12 +23,46 @@ import { WorkflowVersionStatus } from 'src/engine/core-modules/workflow/entities
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 UniversalFlatWorkflow } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-workflow.type';
+import { type UniversalFlatWorkflowVersion } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-workflow-version.type';
+import { type WorkflowTrigger } from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';
+
+const fromFlatWorkflowVersionToUniversalFlatWorkflowVersion = ({
+ workspaceId: _workspaceId,
+ applicationId: _applicationId,
+ ...universalFlatWorkflowVersion
+}: FlatWorkflowVersion): UniversalFlatWorkflowVersion & { id: string } =>
+ universalFlatWorkflowVersion;
+
+const buildPublishedFlatUniversalWorkflowVersion = ({
+ trigger,
+ ...version
+}: Pick<
+ UniversalFlatWorkflowVersion,
+ | 'universalIdentifier'
+ | 'applicationUniversalIdentifier'
+ | 'coreWorkflowId'
+ | 'workflowId'
+ | 'steps'
+ | 'createdAt'
+ | 'updatedAt'
+> & {
+ id: string;
+ trigger: WorkflowTrigger;
+}): UniversalFlatWorkflowVersion & { id: string } => ({
+ ...version,
+ workspaceWorkflowVersionId: null,
+ isSystemSideEffect: true,
+ status: WorkflowVersionStatus.ACTIVE,
+ triggers: [trigger],
+});
export const fromWorkflowManifestToUniversalFlatWorkflowOrThrow = ({
manifest,
applicationUniversalIdentifier,
existingWorkflow,
existingVersion,
+ activeVersion,
+ isWorkspaceCustomApplication = false,
now,
...references
}: {
@@ -35,6 +70,8 @@ export const fromWorkflowManifestToUniversalFlatWorkflowOrThrow = ({
applicationUniversalIdentifier: string;
existingWorkflow?: FlatWorkflow;
existingVersion?: FlatWorkflowVersion;
+ activeVersion?: FlatWorkflowVersion;
+ isWorkspaceCustomApplication?: boolean;
now: string;
} & WorkflowManifestReferences): UniversalFlatWorkflow & { id: string } => {
const parsed = z
@@ -48,21 +85,7 @@ export const fromWorkflowManifestToUniversalFlatWorkflowOrThrow = ({
);
}
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 }),
@@ -72,6 +95,35 @@ export const fromWorkflowManifestToUniversalFlatWorkflowOrThrow = ({
trigger: definition.version.trigger,
references,
});
+
+ const keptActiveVersion =
+ isDefined(activeVersion) &&
+ isSameWorkflowVersionDefinition(activeVersion, {
+ triggers: [trigger],
+ steps,
+ })
+ ? activeVersion
+ : undefined;
+ // Each changed definition of a builder-published workflow is a new version, so runs keep what they ran
+ const flatUniversalWorkflowVersion = isDefined(keptActiveVersion)
+ ? fromFlatWorkflowVersionToUniversalFlatWorkflowVersion(keptActiveVersion)
+ : buildPublishedFlatUniversalWorkflowVersion({
+ id: existingVersion?.id ?? v4(),
+ universalIdentifier: isWorkspaceCustomApplication
+ ? v4()
+ : getWorkflowVersionUniversalIdentifier({
+ applicationUniversalIdentifier,
+ workflowUniversalIdentifier: definition.universalIdentifier,
+ }),
+ applicationUniversalIdentifier,
+ coreWorkflowId: workflowId,
+ workflowId: existingWorkflow?.workspaceWorkflowId ?? null,
+ trigger,
+ steps,
+ createdAt: existingVersion?.createdAt ?? now,
+ updatedAt: now,
+ });
+ const versionId = flatUniversalWorkflowVersion.id;
const commandMenuItem = fromWorkflowManifestToUniversalFlatCommandMenuItem({
manifest: definition,
applicationUniversalIdentifier,
@@ -87,27 +139,18 @@ export const fromWorkflowManifestToUniversalFlatWorkflowOrThrow = ({
visibility: WorkflowVisibility.WORKSPACE,
createdByUserWorkspaceId: null,
workspaceWorkflowId: null,
- lastPublishedVersionId: null,
+ lastPublishedVersionId: isDefined(keptActiveVersion)
+ ? (existingWorkflow?.lastPublishedVersionId ?? null)
+ : null,
lastPublishedCoreWorkflowVersionId: versionId,
createdAt: existingWorkflow?.createdAt ?? now,
updatedAt: now,
- versionDefinitionHash: createHash('sha256')
- .update(JSON.stringify(sortKeysDeeply({ 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,
- },
+ versionDefinitionHash: isDefined(keptActiveVersion)
+ ? (existingWorkflow?.versionDefinitionHash ?? null)
+ : createHash('sha256')
+ .update(JSON.stringify(sortKeysDeeply({ trigger, steps })))
+ .digest('hex'),
+ flatUniversalWorkflowVersion,
...(isDefined(commandMenuItem)
? { flatUniversalCommandMenuItem: commandMenuItem }
: {}),
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/application-manifest-export.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/application-manifest-export.service.ts
index 12c0d96c716..c8224ab20e0 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/application-manifest-export.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/application-manifest-export.service.ts
@@ -159,7 +159,7 @@ export class ApplicationManifestExportService {
allFlatEntityMaps,
exportedObjectUniversalIdentifiers,
resolvableFieldUniversalIdentifiers,
- canReferenceOtherApplicationsWorkflowActions:
+ isWorkspaceCustomApplication:
flatApplication.id === workspaceCustomFlatApplication.id,
});
const { agents, coverage: agentsCoverage } = reconstructAgentsManifest({
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
index 3867093dcbb..11c9d1265cd 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
@@ -1,6 +1,7 @@
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 { type FlatWorkflow } from 'src/engine/metadata-modules/flat-workflow/types/flat-workflow.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';
@@ -39,6 +40,7 @@ const MANIFEST = buildBaseManifest({
const compute = ({
workflows = MANIFEST.workflows ?? [],
fromAllFlatEntityMaps = createEmptyAllFlatEntityMaps(),
+ isWorkspaceCustomApplication = false,
} = {}) => {
for (const workflow of Object.values(
fromAllFlatEntityMaps.flatWorkflowMaps.byUniversalIdentifier,
@@ -63,7 +65,7 @@ const compute = ({
toAllUniversalFlatEntityMaps,
existingAllFlatEntityMaps: fromAllFlatEntityMaps,
idByUniversalIdentifierByMetadataName: {},
- canReferenceOtherApplicationsWorkflowActions: false,
+ isWorkspaceCustomApplication,
now: '2026-09-28T00:00:00.000Z',
});
@@ -148,4 +150,85 @@ describe('application workflow manifest updates', () => {
compute({ workflows, fromAllFlatEntityMaps: existing }),
).toThrow(/unknown record field missing.*fieldsToUpdate/);
});
+
+ describe('workspace custom application', () => {
+ const WORKFLOW_UNIVERSAL_IDENTIFIER =
+ '33333333-3333-4333-8333-333333333333';
+ const LEGACY_WORKFLOW_ID = '77777777-7777-4777-8777-777777777777';
+
+ const publishedFromBuilder = () => {
+ const published = compute({ isWorkspaceCustomApplication: true });
+ const workflow = published.flatWorkflowMaps.byUniversalIdentifier[
+ WORKFLOW_UNIVERSAL_IDENTIFIER
+ ] as UniversalFlatWorkflow & FlatWorkflow;
+
+ published.flatWorkflowMaps.byUniversalIdentifier[
+ WORKFLOW_UNIVERSAL_IDENTIFIER
+ ] = {
+ ...workflow,
+ versionDefinitionHash: null,
+ lastPublishedVersionId: 'legacy-workflow-version-id',
+ workspaceWorkflowId: LEGACY_WORKFLOW_ID,
+ };
+
+ return { published, version: workflow.flatUniversalWorkflowVersion };
+ };
+ const syncedWorkflow = (maps: ReturnType<typeof compute>) =>
+ maps.flatWorkflowMaps.byUniversalIdentifier[
+ WORKFLOW_UNIVERSAL_IDENTIFIER
+ ] as UniversalFlatWorkflow;
+
+ it('keeps the active version and its pointers when the definition matches it', () => {
+ const { published, version } = publishedFromBuilder();
+
+ const workflow = syncedWorkflow(
+ compute({
+ fromAllFlatEntityMaps: published,
+ isWorkspaceCustomApplication: true,
+ }),
+ );
+
+ expect(workflow).toMatchObject({
+ versionDefinitionHash: null,
+ lastPublishedVersionId: 'legacy-workflow-version-id',
+ lastPublishedCoreWorkflowVersionId: version?.id,
+ });
+ expect(workflow.flatUniversalWorkflowVersion).toEqual(version);
+ });
+
+ it('publishes a changed definition as a new version of the workflow', () => {
+ const { published, version } = publishedFromBuilder();
+ const workflows = structuredClone(MANIFEST.workflows ?? []);
+ const [step] = workflows[0]?.version.steps ?? [];
+
+ if (!isDefined(step)) {
+ throw new Error('Expected step');
+ }
+ step.name = 'Changed';
+
+ const workflow = syncedWorkflow(
+ compute({
+ workflows,
+ fromAllFlatEntityMaps: published,
+ isWorkspaceCustomApplication: true,
+ }),
+ );
+
+ expect(workflow.flatUniversalWorkflowVersion).toMatchObject({
+ status: 'ACTIVE',
+ workflowId: LEGACY_WORKFLOW_ID,
+ steps: [{ name: 'Changed' }],
+ });
+ expect(workflow.flatUniversalWorkflowVersion?.id).not.toBe(version?.id);
+ expect(
+ workflow.flatUniversalWorkflowVersion?.universalIdentifier,
+ ).not.toBe(version?.universalIdentifier);
+ expect(workflow).toMatchObject({
+ lastPublishedVersionId: null,
+ lastPublishedCoreWorkflowVersionId:
+ workflow.flatUniversalWorkflowVersion?.id,
+ });
+ expect(workflow.versionDefinitionHash).toEqual(expect.any(String));
+ });
+ });
});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/build-application-workflow-cron-trigger-cache-entries.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/build-application-workflow-cron-trigger-cache-entries.util.spec.ts
index 7ed4109c6d8..8aa03795611 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/build-application-workflow-cron-trigger-cache-entries.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/build-application-workflow-cron-trigger-cache-entries.util.spec.ts
@@ -6,11 +6,33 @@ import {
const WORKSPACE_ID = '20202020-1c25-4d02-bf25-6aeccf7ea419';
-const applicationWorkflow = (id: string, trigger: WorkflowTrigger) => ({
+const SCHEDULE_TRIGGER: WorkflowTrigger = {
+ name: 'On a schedule',
+ type: WorkflowTriggerType.CRON,
+ settings: {
+ type: 'HOURS',
+ schedule: { hour: 2, minute: 30 },
+ outputSchema: {},
+ },
+};
+
+const applicationWorkflow = ({
+ id,
+ trigger,
+ workflowId = null,
+ workspaceWorkflowVersionId = null,
+}: {
+ id: string;
+ trigger: WorkflowTrigger;
+ workflowId?: string | null;
+ workspaceWorkflowVersionId?: string | null;
+}) => ({
id,
flatUniversalWorkflowVersion: {
id: `${id.slice(0, -1)}9`,
triggers: [trigger],
+ workflowId,
+ workspaceWorkflowVersionId,
},
});
@@ -19,19 +41,17 @@ describe('buildApplicationWorkflowCronTriggerCacheEntries', () => {
const entries = buildApplicationWorkflowCronTriggerCacheEntries({
workspaceId: WORKSPACE_ID,
workflows: [
- applicationWorkflow('11111111-1111-4111-8111-111111111111', {
- name: 'On a schedule',
- type: WorkflowTriggerType.CRON,
- settings: {
- type: 'HOURS',
- schedule: { hour: 2, minute: 30 },
- outputSchema: {},
- },
+ applicationWorkflow({
+ id: '11111111-1111-4111-8111-111111111111',
+ trigger: SCHEDULE_TRIGGER,
}),
- applicationWorkflow('22222222-2222-4222-8222-222222222222', {
- name: 'Manual trigger',
- type: WorkflowTriggerType.MANUAL,
- settings: { outputSchema: {} },
+ applicationWorkflow({
+ id: '22222222-2222-4222-8222-222222222222',
+ trigger: {
+ name: 'Manual trigger',
+ type: WorkflowTriggerType.MANUAL,
+ settings: { outputSchema: {} },
+ },
}),
],
});
@@ -45,4 +65,29 @@ describe('buildApplicationWorkflowCronTriggerCacheEntries', () => {
},
]);
});
+
+ it('keeps the legacy identifiers of a workflow first published in the workspace', () => {
+ expect(
+ buildApplicationWorkflowCronTriggerCacheEntries({
+ workspaceId: WORKSPACE_ID,
+ workflows: [
+ applicationWorkflow({
+ id: '33333333-3333-4333-8333-333333333333',
+ trigger: SCHEDULE_TRIGGER,
+ workflowId: '44444444-4444-4444-8444-444444444444',
+ workspaceWorkflowVersionId: '55555555-5555-4555-8555-555555555555',
+ }),
+ ],
+ }),
+ ).toEqual([
+ {
+ workspaceId: WORKSPACE_ID,
+ workflowId: '33333333-3333-4333-8333-333333333333',
+ legacyWorkflowId: '44444444-4444-4444-8444-444444444444',
+ coreWorkflowVersionId: '33333333-3333-4333-8333-333333333339',
+ workspaceWorkflowVersionId: '55555555-5555-4555-8555-555555555555',
+ pattern: '30 */2 * * *',
+ },
+ ]);
+ });
});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/classify-application-flat-entities.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/classify-application-flat-entities.util.spec.ts
index 750e4923f3c..232e96d1643 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/classify-application-flat-entities.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/classify-application-flat-entities.util.spec.ts
@@ -17,6 +17,7 @@ import { getFlatObjectMetadataMock } from 'src/engine/metadata-modules/flat-obje
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
import { type FlatRole } from 'src/engine/metadata-modules/flat-role/types/flat-role.type';
import { type FlatRoleTarget } from 'src/engine/metadata-modules/flat-role-target/types/flat-role-target.type';
+import { type FlatWorkflowVersion } from 'src/engine/metadata-modules/flat-workflow-version/types/flat-workflow-version.type';
const APP_ID = 'application-id';
const APP_UID = '11111111-1111-4111-8111-111111111111';
@@ -354,3 +355,37 @@ describe('classifyApplicationFlatEntities workflow commands', () => {
});
});
});
+
+describe('classifyApplicationFlatEntities workflow versions', () => {
+ it('should exclude a version published from the workflow builder, which its workflow exports', () => {
+ const workflowVersionUniversalIdentifier =
+ 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
+ const maps = createEmptyAllFlatEntityMaps();
+
+ maps.flatWorkflowVersionMaps = addFlatEntityToFlatEntityMapsOrThrow({
+ flatEntity: {
+ id: 'workflow-version-id',
+ universalIdentifier: workflowVersionUniversalIdentifier,
+ applicationId: APP_ID,
+ applicationUniversalIdentifier: APP_UID,
+ isSystemSideEffect: false,
+ } as FlatWorkflowVersion,
+ flatEntityMaps: maps.flatWorkflowVersionMaps,
+ });
+
+ expect(
+ classifyApplicationFlatEntities({
+ flatApplication,
+ allFlatEntityMaps: maps,
+ applicationAllFlatEntityMaps: maps,
+ reconstructedCoverage: [],
+ }).find(
+ (entry) =>
+ entry.universalIdentifier === workflowVersionUniversalIdentifier,
+ ),
+ ).toMatchObject({
+ status: ApplicationExportCoverageStatus.EXCLUDED,
+ reason: 'workflow version, exported through its workflow',
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/export-covers-compared-properties.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/export-covers-compared-properties.spec.ts
index b35b1c5c0af..39c0c27438a 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/export-covers-compared-properties.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/export-covers-compared-properties.spec.ts
@@ -845,15 +845,13 @@ const EXPORTED_KINDS: ExportedKind[] = [
exportWorkflowManifestOrThrow(WORKFLOW_MANIFEST),
),
renamedProperties: { versionDefinitionHash: 'version' },
- workspaceLocalProperties: [],
+ workspaceLocalProperties: ['visibility'],
knownGaps: {
isSystem: 'system workflows are reported as excluded',
- visibility:
- 'private workflows are reported as excluded, exported workflows are visible to the workspace',
lastPublishedVersionId:
- 'legacy workspace version pointer, always null for synced application workflows',
+ 'legacy workspace version pointer, kept while the active version matches the definition',
lastPublishedCoreWorkflowVersionId:
- 'the sync points it at the version it derives from the definition',
+ 'the sync points it at the active version, or at the one it publishes from the definition',
},
},
{
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-workflows-manifest.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-workflows-manifest.util.spec.ts
index d1594cc779b..8128b936a8f 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-workflows-manifest.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-workflows-manifest.util.spec.ts
@@ -236,10 +236,10 @@ const buildMaps = ({
const reconstruct = ({
synced,
- canReferenceOtherApplicationsWorkflowActions = false,
+ isWorkspaceCustomApplication = false,
}: {
synced: ReturnType<typeof syncWorkflow>[];
- canReferenceOtherApplicationsWorkflowActions?: boolean;
+ isWorkspaceCustomApplication?: boolean;
}) =>
reconstructWorkflowsManifest({
applicationAllFlatEntityMaps: buildMaps({
@@ -253,7 +253,7 @@ const reconstruct = ({
}),
exportedObjectUniversalIdentifiers: new Set([TICKET_UID]),
resolvableFieldUniversalIdentifiers: new Set(),
- canReferenceOtherApplicationsWorkflowActions,
+ isWorkspaceCustomApplication,
});
describe('reconstructWorkflowsManifest', () => {
@@ -314,10 +314,6 @@ describe('reconstructWorkflowsManifest', () => {
manifest: manifest('b4000000-0000-4000-8000-000000000000'),
workflowOverrides: { lastPublishedCoreWorkflowVersionId: null },
}),
- syncWorkflow({
- manifest: manifest('b5000000-0000-4000-8000-000000000000'),
- workflowOverrides: { workspaceWorkflowId: 'workspace-workflow-id' },
- }),
syncWorkflow({
manifest: createRecordWorkflow({
universalIdentifier: 'b6000000-0000-4000-8000-000000000000',
@@ -357,12 +353,6 @@ describe('reconstructWorkflowsManifest', () => {
status: ApplicationExportCoverageStatus.UNSUPPORTED,
reason: 'workflow changed in the workflow builder',
})),
- {
- metadataName: 'workflow',
- universalIdentifier: 'b5000000-0000-4000-8000-000000000000',
- status: ApplicationExportCoverageStatus.UNSUPPORTED,
- reason: 'workflow created in the workspace',
- },
{
metadataName: 'workflow',
universalIdentifier: 'b6000000-0000-4000-8000-000000000000',
@@ -399,7 +389,7 @@ describe('reconstructWorkflowsManifest', () => {
expect(
reconstruct({
synced,
- canReferenceOtherApplicationsWorkflowActions: true,
+ isWorkspaceCustomApplication: true,
}).workflows,
).toEqual([manifest]);
});
@@ -426,7 +416,7 @@ describe('reconstructWorkflowsManifest', () => {
allFlatEntityMaps: mapsWithWorkflow,
exportedObjectUniversalIdentifiers: new Set([TICKET_UID]),
resolvableFieldUniversalIdentifiers: new Set(),
- canReferenceOtherApplicationsWorkflowActions: false,
+ isWorkspaceCustomApplication: false,
}).coverage,
).toEqual([
{
@@ -437,4 +427,107 @@ describe('reconstructWorkflowsManifest', () => {
},
]);
});
+
+ describe('workspace custom application', () => {
+ const builderWorkflow = ({
+ universalIdentifier,
+ versionOverrides = {},
+ }: {
+ universalIdentifier: string;
+ versionOverrides?: Partial<FlatWorkflowVersion>;
+ }) => {
+ const builderVersionId = `9${universalIdentifier.slice(1)}`;
+
+ return syncWorkflow({
+ manifest: createRecordWorkflow({
+ universalIdentifier,
+ objectUniversalIdentifier: TICKET_UID,
+ }),
+ workflowOverrides: {
+ lastPublishedCoreWorkflowVersionId: builderVersionId,
+ versionDefinitionHash: null,
+ workspaceWorkflowId: 'workspace-workflow-id',
+ createdByUserWorkspaceId: 'user-workspace-id',
+ },
+ versionOverrides: {
+ id: builderVersionId,
+ universalIdentifier: `8${universalIdentifier.slice(1)}`,
+ isSystemSideEffect: false,
+ workspaceWorkflowVersionId: 'workspace-workflow-version-id',
+ ...versionOverrides,
+ },
+ });
+ };
+
+ it('exports the active version published from the workflow builder', () => {
+ const synced = builderWorkflow({
+ universalIdentifier: 'e0000000-0000-4000-8000-000000000000',
+ });
+
+ expect(
+ reconstruct({ synced: [synced], isWorkspaceCustomApplication: true }),
+ ).toEqual({
+ workflows: [
+ createRecordWorkflow({
+ universalIdentifier: 'e0000000-0000-4000-8000-000000000000',
+ objectUniversalIdentifier: TICKET_UID,
+ }),
+ ],
+ coverage: [
+ {
+ metadataName: 'workflow',
+ universalIdentifier: 'e0000000-0000-4000-8000-000000000000',
+ status: ApplicationExportCoverageStatus.EXPORTED,
+ },
+ ],
+ });
+ expect(reconstruct({ synced: [synced] }).coverage).toEqual([
+ {
+ metadataName: 'workflow',
+ universalIdentifier: 'e0000000-0000-4000-8000-000000000000',
+ status: ApplicationExportCoverageStatus.UNSUPPORTED,
+ reason: 'workflow changed in the workflow builder',
+ },
+ ]);
+ });
+
+ it('reports a builder workflow without an active version or that a manifest cannot reproduce', () => {
+ const deactivated = builderWorkflow({
+ universalIdentifier: 'e1000000-0000-4000-8000-000000000000',
+ versionOverrides: { status: WorkflowVersionStatus.DEACTIVATED },
+ });
+ const renamedTrigger = builderWorkflow({
+ universalIdentifier: 'e2000000-0000-4000-8000-000000000000',
+ });
+ const [trigger] = renamedTrigger.flatWorkflowVersion.triggers ?? [];
+
+ renamedTrigger.flatWorkflowVersion = {
+ ...renamedTrigger.flatWorkflowVersion,
+ triggers: [{ ...trigger, name: 'Launch manually' }],
+ };
+
+ expect(
+ reconstruct({
+ synced: [deactivated, renamedTrigger],
+ isWorkspaceCustomApplication: true,
+ }),
+ ).toEqual({
+ workflows: [],
+ coverage: [
+ {
+ metadataName: 'workflow',
+ universalIdentifier: 'e1000000-0000-4000-8000-000000000000',
+ status: ApplicationExportCoverageStatus.UNSUPPORTED,
+ reason: 'workflow without an active version',
+ },
+ {
+ metadataName: 'workflow',
+ universalIdentifier: 'e2000000-0000-4000-8000-000000000000',
+ status: ApplicationExportCoverageStatus.UNSUPPORTED,
+ reason: 'workflow with settings a manifest cannot reproduce',
+ },
+ ],
+ });
+ });
+ });
});
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
index 44ee82cd303..e1e78af1813 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,8 +4,10 @@ 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 { findActiveFlatWorkflowVersionByWorkflowId } from 'src/engine/core-modules/application/application-manifest/utils/find-active-flat-workflow-version-by-workflow-id.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 {
@@ -14,10 +16,35 @@ import {
} 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 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';
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';
+// The workspace custom application publishes from the active version, not a managed one
+const findManagedFlatWorkflowVersion = ({
+ flatWorkflowVersionMaps,
+ applicationUniversalIdentifier,
+ workflowUniversalIdentifier,
+ isWorkspaceCustomApplication,
+}: {
+ flatWorkflowVersionMaps: AllFlatEntityMaps['flatWorkflowVersionMaps'];
+ applicationUniversalIdentifier: string;
+ workflowUniversalIdentifier: string;
+ isWorkspaceCustomApplication: boolean;
+}): FlatWorkflowVersion | undefined => {
+ if (isWorkspaceCustomApplication) {
+ return undefined;
+ }
+
+ return flatWorkflowVersionMaps.byUniversalIdentifier[
+ getWorkflowVersionUniversalIdentifier({
+ applicationUniversalIdentifier,
+ workflowUniversalIdentifier,
+ })
+ ];
+};
+
export const addWorkflowManifestsToFlatEntityMapsOrThrow = ({
workflows,
ownerFlatApplication,
@@ -25,7 +52,7 @@ export const addWorkflowManifestsToFlatEntityMapsOrThrow = ({
toAllUniversalFlatEntityMaps,
existingAllFlatEntityMaps,
idByUniversalIdentifierByMetadataName,
- canReferenceOtherApplicationsWorkflowActions,
+ isWorkspaceCustomApplication,
now,
}: {
workflows: WorkflowManifest[];
@@ -34,7 +61,7 @@ export const addWorkflowManifestsToFlatEntityMapsOrThrow = ({
toAllUniversalFlatEntityMaps: AllFlatEntityMaps;
existingAllFlatEntityMaps: AllFlatEntityMaps;
idByUniversalIdentifierByMetadataName: IdByUniversalIdentifierByMetadataName;
- canReferenceOtherApplicationsWorkflowActions: boolean;
+ isWorkspaceCustomApplication: boolean;
now: string;
}): (UniversalFlatWorkflow & { id: string })[] => {
const applicationUniversalIdentifier =
@@ -47,26 +74,36 @@ export const addWorkflowManifestsToFlatEntityMapsOrThrow = ({
existingAllFlatEntityMaps,
ownerApplicationId: ownerFlatApplication.id,
idByUniversalIdentifierByMetadataName,
- canReferenceOtherApplicationsWorkflowActions,
+ // Its workflows run as workspace workflows, which may already call any app's actions
+ canReferenceOtherApplicationsWorkflowActions:
+ isWorkspaceCustomApplication,
});
+ const activeVersionByWorkflowId = isWorkspaceCustomApplication
+ ? findActiveFlatWorkflowVersionByWorkflowId(
+ fromAllFlatEntityMaps.flatWorkflowVersionMaps,
+ )
+ : new Map<string, FlatWorkflowVersion>();
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 existingVersion = findManagedFlatWorkflowVersion({
+ flatWorkflowVersionMaps: fromAllFlatEntityMaps.flatWorkflowVersionMaps,
+ applicationUniversalIdentifier,
+ workflowUniversalIdentifier: workflowManifest.universalIdentifier,
+ isWorkspaceCustomApplication,
+ });
const workflow = fromWorkflowManifestToUniversalFlatWorkflowOrThrow({
manifest: workflowManifest,
applicationUniversalIdentifier,
existingWorkflow,
existingVersion,
+ activeVersion: isDefined(existingWorkflow)
+ ? activeVersionByWorkflowId.get(existingWorkflow.id)
+ : undefined,
+ isWorkspaceCustomApplication,
...references,
now,
});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-application-workflow-cron-trigger-cache-entries.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-application-workflow-cron-trigger-cache-entries.util.ts
index 6839d036cbc..00d04647ac7 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-application-workflow-cron-trigger-cache-entries.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-application-workflow-cron-trigger-cache-entries.util.ts
@@ -15,7 +15,7 @@ export const buildApplicationWorkflowCronTriggerCacheEntries = ({
id: string;
flatUniversalWorkflowVersion?: Pick<
UniversalFlatWorkflowVersion,
- 'triggers'
+ 'triggers' | 'workflowId' | 'workspaceWorkflowVersionId'
> & { id: string };
}[];
}): CachedCronTrigger[] =>
@@ -31,8 +31,14 @@ export const buildApplicationWorkflowCronTriggerCacheEntries = ({
{
workspaceId,
workflowId: workflow.id,
+ ...(isDefined(version.workflowId)
+ ? { legacyWorkflowId: version.workflowId }
+ : {}),
pattern: computeCronPatternFromSchedule(trigger),
- ...buildCoreDispatchIds({ coreWorkflowVersionId: version.id }),
+ ...buildCoreDispatchIds({
+ coreWorkflowVersionId: version.id,
+ workspaceWorkflowVersionId: version.workspaceWorkflowVersionId,
+ }),
},
];
});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/classify-application-flat-entities.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/classify-application-flat-entities.util.ts
index dd81bd4d870..0dfd65a3942 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/classify-application-flat-entities.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/classify-application-flat-entities.util.ts
@@ -84,6 +84,11 @@ const classifyFlatEntity = ({
: { status: ApplicationExportCoverageStatus.UNSUPPORTED };
case 'searchFieldMetadata':
return { status: ApplicationExportCoverageStatus.ENGINE_DERIVED };
+ case 'workflowVersion':
+ return {
+ status: ApplicationExportCoverageStatus.EXCLUDED,
+ reason: 'workflow version, exported through its workflow',
+ };
case 'roleTarget':
return ('userWorkspaceId' in flatEntity &&
isDefined(flatEntity.userWorkspaceId)) ||
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/find-active-flat-workflow-version-by-workflow-id.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/find-active-flat-workflow-version-by-workflow-id.util.ts
new file mode 100644
index 00000000000..f826be522ec
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/find-active-flat-workflow-version-by-workflow-id.util.ts
@@ -0,0 +1,26 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { WorkflowVersionStatus } from 'src/engine/core-modules/workflow/entities/workflow-version.entity';
+import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
+import { type FlatWorkflowVersion } from 'src/engine/metadata-modules/flat-workflow-version/types/flat-workflow-version.type';
+
+export const findActiveFlatWorkflowVersionByWorkflowId = (
+ flatWorkflowVersionMaps: AllFlatEntityMaps['flatWorkflowVersionMaps'],
+): Map<string, FlatWorkflowVersion> =>
+ new Map(
+ Object.values(flatWorkflowVersionMaps.byUniversalIdentifier)
+ .filter(isDefined)
+ .filter(
+ (
+ flatWorkflowVersion,
+ ): flatWorkflowVersion is FlatWorkflowVersion & {
+ coreWorkflowId: string;
+ } =>
+ flatWorkflowVersion.status === WorkflowVersionStatus.ACTIVE &&
+ isDefined(flatWorkflowVersion.coreWorkflowId),
+ )
+ .map((flatWorkflowVersion) => [
+ flatWorkflowVersion.coreWorkflowId,
+ flatWorkflowVersion,
+ ]),
+ );
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/is-same-workflow-version-definition.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/is-same-workflow-version-definition.util.ts
new file mode 100644
index 00000000000..969937d41af
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/is-same-workflow-version-definition.util.ts
@@ -0,0 +1,19 @@
+import isEqual from 'lodash.isequal';
+
+import { type UniversalFlatWorkflowVersion } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-workflow-version.type';
+
+type WorkflowVersionDefinition = Pick<
+ UniversalFlatWorkflowVersion,
+ 'triggers' | 'steps'
+>;
+
+// Compared as stored in jsonb, where undefined properties are dropped
+const toJsonValue = ({ triggers, steps }: WorkflowVersionDefinition): unknown =>
+ JSON.parse(
+ JSON.stringify({ triggers: triggers ?? null, steps: steps ?? null }),
+ );
+
+export const isSameWorkflowVersionDefinition = (
+ left: WorkflowVersionDefinition,
+ right: WorkflowVersionDefinition,
+): boolean => isEqual(toJsonValue(left), toJsonValue(right));
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/reconstruct-workflows-manifest.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/reconstruct-workflows-manifest.util.ts
index f91a64aac1d..5e8745831e4 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/reconstruct-workflows-manifest.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/reconstruct-workflows-manifest.util.ts
@@ -14,33 +14,70 @@ import { sortFlatEntitiesByUniversalIdentifier } from 'src/engine/core-modules/a
import { ApplicationExportCoverageStatus } from 'src/engine/core-modules/application/enums/application-export-coverage-status.enum';
import { WorkflowVersionStatus } from 'src/engine/core-modules/workflow/entities/workflow-version.entity';
import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
+import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.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 findSyncedFlatWorkflowVersion = ({
+type ExportedFlatWorkflow = Pick<
+ FlatWorkflow,
+ | 'applicationUniversalIdentifier'
+ | 'universalIdentifier'
+ | 'lastPublishedCoreWorkflowVersionId'
+>;
+
+// The builder publishes workspace custom application workflows too, under any version identifier
+const findPublishedFlatWorkflowVersionCandidate = ({
flatWorkflow,
- allFlatEntityMaps,
+ lastPublishedCoreWorkflowVersionId,
+ flatWorkflowVersionMaps,
+ isWorkspaceCustomApplication,
+}: {
+ flatWorkflow: ExportedFlatWorkflow;
+ lastPublishedCoreWorkflowVersionId: string;
+ flatWorkflowVersionMaps: AllFlatEntityMaps['flatWorkflowVersionMaps'];
+ isWorkspaceCustomApplication: boolean;
+}): FlatWorkflowVersion | undefined => {
+ if (isWorkspaceCustomApplication) {
+ return findFlatEntityByIdInFlatEntityMaps({
+ flatEntityId: lastPublishedCoreWorkflowVersionId,
+ flatEntityMaps: flatWorkflowVersionMaps,
+ });
+ }
+
+ return flatWorkflowVersionMaps.byUniversalIdentifier[
+ getWorkflowVersionUniversalIdentifier({
+ applicationUniversalIdentifier:
+ flatWorkflow.applicationUniversalIdentifier,
+ workflowUniversalIdentifier: flatWorkflow.universalIdentifier,
+ })
+ ];
+};
+
+const findExportedFlatWorkflowVersion = ({
+ flatWorkflow,
+ allFlatEntityMaps: { flatWorkflowVersionMaps },
+ isWorkspaceCustomApplication,
}: {
- flatWorkflow: Pick<
- FlatWorkflow,
- | 'applicationUniversalIdentifier'
- | 'universalIdentifier'
- | 'lastPublishedCoreWorkflowVersionId'
- >;
+ flatWorkflow: ExportedFlatWorkflow;
allFlatEntityMaps: Pick<AllFlatEntityMaps, 'flatWorkflowVersionMaps'>;
+ isWorkspaceCustomApplication: boolean;
}): FlatWorkflowVersion | undefined => {
- const flatWorkflowVersion =
- allFlatEntityMaps.flatWorkflowVersionMaps.byUniversalIdentifier[
- getWorkflowVersionUniversalIdentifier({
- applicationUniversalIdentifier:
- flatWorkflow.applicationUniversalIdentifier,
- workflowUniversalIdentifier: flatWorkflow.universalIdentifier,
- })
- ];
+ const { lastPublishedCoreWorkflowVersionId } = flatWorkflow;
+
+ if (!isDefined(lastPublishedCoreWorkflowVersionId)) {
+ return undefined;
+ }
+
+ const flatWorkflowVersion = findPublishedFlatWorkflowVersionCandidate({
+ flatWorkflow,
+ lastPublishedCoreWorkflowVersionId,
+ flatWorkflowVersionMaps,
+ isWorkspaceCustomApplication,
+ });
return isDefined(flatWorkflowVersion) &&
flatWorkflowVersion.status === WorkflowVersionStatus.ACTIVE &&
- flatWorkflowVersion.id === flatWorkflow.lastPublishedCoreWorkflowVersionId
+ flatWorkflowVersion.id === lastPublishedCoreWorkflowVersionId
? flatWorkflowVersion
: undefined;
};
@@ -50,13 +87,13 @@ export const reconstructWorkflowsManifest = ({
allFlatEntityMaps,
exportedObjectUniversalIdentifiers,
resolvableFieldUniversalIdentifiers,
- canReferenceOtherApplicationsWorkflowActions,
+ isWorkspaceCustomApplication,
}: {
applicationAllFlatEntityMaps: AllFlatEntityMaps;
allFlatEntityMaps: AllFlatEntityMaps;
exportedObjectUniversalIdentifiers: ReadonlySet<string>;
resolvableFieldUniversalIdentifiers: ReadonlySet<string>;
- canReferenceOtherApplicationsWorkflowActions: boolean;
+ isWorkspaceCustomApplication: boolean;
}): {
workflows: WorkflowManifest[];
coverage: ApplicationExportCoverageEntry[];
@@ -68,7 +105,7 @@ export const reconstructWorkflowsManifest = ({
allFlatEntityMaps,
exportedObjectUniversalIdentifiers,
resolvableFieldUniversalIdentifiers,
- canReferenceOtherApplicationsWorkflowActions,
+ canReferenceOtherApplicationsWorkflowActions: isWorkspaceCustomApplication,
});
const getExclusionReason = (flatWorkflow: FlatWorkflow) => {
@@ -84,23 +121,30 @@ export const reconstructWorkflowsManifest = ({
const convertFlatWorkflow = (
flatWorkflow: FlatWorkflow,
): { manifest: WorkflowManifest } | { reason: string } => {
- if (isDefined(flatWorkflow.workspaceWorkflowId)) {
- return { reason: 'workflow created in the workspace' };
- }
-
- const flatWorkflowVersion = findSyncedFlatWorkflowVersion({
+ const flatWorkflowVersion = findExportedFlatWorkflowVersion({
flatWorkflow,
allFlatEntityMaps,
+ isWorkspaceCustomApplication,
});
if (!isDefined(flatWorkflowVersion)) {
- return { reason: WORKFLOW_CHANGED_IN_BUILDER_REASON };
+ return {
+ reason: isWorkspaceCustomApplication
+ ? 'workflow without an active version'
+ : WORKFLOW_CHANGED_IN_BUILDER_REASON,
+ };
}
return fromFlatWorkflowToWorkflowManifest({
flatWorkflow,
flatWorkflowVersion,
references,
+ ...(isWorkspaceCustomApplication
+ ? {
+ unreproducibleReason:
+ 'workflow with settings a manifest cannot reproduce',
+ }
+ : {}),
});
};
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.ts
index d1395ad40d4..3f011539471 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.ts
@@ -670,6 +670,14 @@ export class CoreWorkflowLifecycleWorkspaceService {
},
workspaceId,
);
+
+ // Deactivation hides an engine-managed command behind an override instead of deleting it
+ if (!existingCommandMenuItem.isActive) {
+ await this.commandMenuItemService.activate(
+ existingCommandMenuItem.id,
+ workspaceId,
+ );
+ }
} else {
await this.commandMenuItemService.create(
{
diff --git a/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.service.ts b/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.service.ts
index f6749719eca..a28d41e209e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.service.ts
@@ -338,6 +338,68 @@ export class CommandMenuItemService {
);
}
+ async activate(id: string, workspaceId: string): Promise<CommandMenuItemDTO> {
+ const { workspaceCustomFlatApplication } =
+ await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
+ { workspaceId },
+ );
+
+ const { flatCommandMenuItemMaps: existingFlatCommandMenuItemMaps } =
+ await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
+ {
+ workspaceId,
+ flatMapsKeys: ['flatCommandMenuItemMaps'],
+ },
+ );
+
+ const existingFlatCommandMenuItem =
+ findFlatEntityByIdInFlatEntityMapsOrThrow({
+ flatEntityId: id,
+ flatEntityMaps: existingFlatCommandMenuItemMaps,
+ });
+
+ const activatedFlatCommandMenuItem = {
+ ...dispatchIsActiveUpdateToAuthoredOverride({
+ metadataName: 'commandMenuItem',
+ flatEntity: existingFlatCommandMenuItem,
+ isActive: true,
+ authorUniversalIdentifier:
+ workspaceCustomFlatApplication.universalIdentifier,
+ workspaceCustomApplicationUniversalIdentifier:
+ workspaceCustomFlatApplication.universalIdentifier,
+ }),
+ updatedAt: new Date().toISOString(),
+ };
+
+ const validateAndBuildResult =
+ await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigration(
+ {
+ allFlatEntityOperationByMetadataName: {
+ commandMenuItem: {
+ flatEntityToCreate: [],
+ flatEntityToDelete: [],
+ flatEntityToUpdate: [activatedFlatCommandMenuItem],
+ },
+ },
+ workspaceId,
+ isSystemBuild: false,
+ applicationUniversalIdentifier:
+ workspaceCustomFlatApplication.universalIdentifier,
+ },
+ );
+
+ if (validateAndBuildResult.status === 'fail') {
+ throw new WorkspaceMigrationBuilderException(
+ validateAndBuildResult,
+ 'Multiple validation errors occurred while activating command menu item',
+ );
+ }
+
+ return fromFlatCommandMenuItemToCommandMenuItemDto(
+ activatedFlatCommandMenuItem,
+ );
+ }
+
async delete(id: string, workspaceId: string): Promise<CommandMenuItemDTO> {
const { workspaceCustomFlatApplication } =
await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/workspace-owned-properties-by-metadata-name.constant.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/workspace-owned-properties-by-metadata-name.constant.ts
index 457068e5795..56618ccc0d3 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/workspace-owned-properties-by-metadata-name.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/workspace-owned-properties-by-metadata-name.constant.ts
@@ -1,15 +1,16 @@
import { type AllMetadataName } from 'twenty-shared/metadata';
-import { type MetadataEntityComparablePropertyName } from 'src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant';
+import { type MetadataEntityPropertyName } from 'src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant';
// Properties a workspace owns on the entities an application ships: the
// application creates them with a default, then leaves whatever the workspace
// chose, instead of resetting it on every synchronization.
export const WORKSPACE_OWNED_PROPERTIES_BY_METADATA_NAME: Partial<{
- [P in AllMetadataName]: MetadataEntityComparablePropertyName<P>[];
+ [P in AllMetadataName]: MetadataEntityPropertyName<P>[];
}> = {
agentChatChannel: ['name', 'icon', 'color', 'position'],
pageLayout: ['isFirstTabPinned'],
skill: ['isActive'],
view: ['createdByUserWorkspaceId'],
+ workflow: ['createdByUserWorkspaceId', 'workspaceWorkflowId', 'visibility'],
};
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
index 3c3eca42cc6..fd1ad9c01ab 100644
--- 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
@@ -1,3 +1,4 @@
+import { WorkflowVersionStatus } from 'src/engine/core-modules/workflow/entities/workflow-version.entity';
import { WorkflowTriggerType } from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';
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';
@@ -293,6 +294,181 @@ describe('application workflow command menu item side effects', () => {
});
});
+describe('workspace custom application workflow version side effects', () => {
+ const BUILDER_VERSION_UNIVERSAL_IDENTIFIER =
+ '88888888-8888-4888-8888-888888888888';
+ const BUILDER_COMMAND_MENU_ITEM_UNIVERSAL_IDENTIFIER =
+ '99999999-9999-4999-8999-999999999999';
+ const manualDefinition = structuredClone(manifest);
+
+ manualDefinition.version.trigger = {
+ ...manifest.version.trigger,
+ type: 'MANUAL',
+ settings: { availability: { type: 'GLOBAL' }, isPinned: true },
+ };
+
+ const publishedFromBuilder = () => {
+ const existing = persisted(convert(manualDefinition));
+ const workflow =
+ existing.flatWorkflowMaps.byUniversalIdentifier[WORKFLOW_ID]!;
+ const { [VERSION_ID]: managedVersion } =
+ existing.flatWorkflowVersionMaps.byUniversalIdentifier;
+ const { [COMMAND_MENU_ITEM_ID]: managedCommandMenuItem } =
+ existing.flatCommandMenuItemMaps.byUniversalIdentifier;
+ const builderVersion = {
+ ...managedVersion!,
+ universalIdentifier: BUILDER_VERSION_UNIVERSAL_IDENTIFIER,
+ isSystemSideEffect: false,
+ };
+
+ existing.flatWorkflowVersionMaps.byUniversalIdentifier = {
+ [BUILDER_VERSION_UNIVERSAL_IDENTIFIER]: builderVersion,
+ };
+ existing.flatCommandMenuItemMaps.byUniversalIdentifier = {
+ [BUILDER_COMMAND_MENU_ITEM_UNIVERSAL_IDENTIFIER]: {
+ ...managedCommandMenuItem!,
+ universalIdentifier: BUILDER_COMMAND_MENU_ITEM_UNIVERSAL_IDENTIFIER,
+ isSystemSideEffect: false,
+ position: 3,
+ },
+ };
+ existing.flatWorkflowMaps.byUniversalIdentifier[WORKFLOW_ID] = {
+ ...workflow,
+ versionDefinitionHash: null,
+ createdByUserWorkspaceId: 'user-workspace-id',
+ };
+
+ return { existing, builderVersion };
+ };
+
+ const convertForWorkspaceCustomApplication = ({
+ definition,
+ existing,
+ }: {
+ definition: WorkflowManifest;
+ existing: Pick<
+ ReturnType<typeof persisted>,
+ 'flatWorkflowMaps' | 'flatWorkflowVersionMaps'
+ >;
+ }) =>
+ fromWorkflowManifestToUniversalFlatWorkflowOrThrow({
+ manifest: definition,
+ applicationUniversalIdentifier: APPLICATION_ID,
+ now: '2026-10-27T10:00:00.000Z',
+ logicFunctionIdByUniversalIdentifier: new Map(),
+ existingWorkflow:
+ existing.flatWorkflowMaps.byUniversalIdentifier[WORKFLOW_ID],
+ activeVersion:
+ existing.flatWorkflowVersionMaps.byUniversalIdentifier[
+ BUILDER_VERSION_UNIVERSAL_IDENTIFIER
+ ],
+ isWorkspaceCustomApplication: true,
+ });
+
+ it('does nothing when the definition matches the active version', () => {
+ const { existing } = publishedFromBuilder();
+ const workflow = convertForWorkspaceCustomApplication({
+ definition: manualDefinition,
+ existing,
+ });
+
+ expect(diff(workflow, existing)).toEqual({});
+ });
+
+ it('archives the active version and publishes the changed definition in the same migration', () => {
+ const { existing, builderVersion } = publishedFromBuilder();
+ const changed = structuredClone(manualDefinition);
+
+ changed.version.steps[0].name = 'Updated step';
+
+ const workflow = convertForWorkspaceCustomApplication({
+ definition: changed,
+ existing,
+ });
+ const version = workflow.flatUniversalWorkflowVersion!;
+ const operations = expand(workflow, existing);
+
+ expect(version.id).not.toBe(builderVersion.id);
+ expect(operations.workflowVersion).toEqual({
+ flatEntityToCreate: { [version.universalIdentifier]: version },
+ flatEntityToUpdate: {
+ [BUILDER_VERSION_UNIVERSAL_IDENTIFIER]: {
+ ...builderVersion,
+ status: 'ARCHIVED',
+ },
+ },
+ });
+ expect(
+ operations.commandMenuItem?.flatEntityToDelete?.[
+ BUILDER_COMMAND_MENU_ITEM_UNIVERSAL_IDENTIFIER
+ ],
+ ).toBeDefined();
+ expect(
+ operations.commandMenuItem?.flatEntityToCreate?.[COMMAND_MENU_ITEM_ID],
+ ).toMatchObject({ coreWorkflowVersionId: version.id });
+ expect(diff(workflow, existing).workflow?.flatEntityToUpdate).toEqual({
+ [WORKFLOW_ID]: expect.objectContaining({
+ lastPublishedCoreWorkflowVersionId: version.id,
+ createdByUserWorkspaceId: 'user-workspace-id',
+ }),
+ });
+ });
+
+ it('keeps the builder trigger command of the active version on a rename', () => {
+ const { existing, builderVersion } = publishedFromBuilder();
+ const workflow = convertForWorkspaceCustomApplication({
+ definition: { ...manualDefinition, name: 'Renamed workflow' },
+ existing,
+ });
+ const operations = expand(workflow, existing);
+
+ expect(operations.workflowVersion).toEqual({
+ flatEntityToUpdate: {
+ [BUILDER_VERSION_UNIVERSAL_IDENTIFIER]: expect.objectContaining({
+ id: builderVersion.id,
+ status: 'ACTIVE',
+ }),
+ },
+ });
+ expect(operations.commandMenuItem).toEqual({
+ flatEntityToDelete: {},
+ flatEntityToUpdate: {
+ [BUILDER_COMMAND_MENU_ITEM_UNIVERSAL_IDENTIFIER]:
+ expect.objectContaining({
+ label: 'Renamed workflow',
+ position: 3,
+ isSystemSideEffect: false,
+ coreWorkflowVersionId: builderVersion.id,
+ }),
+ },
+ });
+ });
+
+ it('publishes the first version of a workflow without an active one', () => {
+ const { existing, builderVersion } = publishedFromBuilder();
+
+ existing.flatWorkflowVersionMaps.byUniversalIdentifier[
+ BUILDER_VERSION_UNIVERSAL_IDENTIFIER
+ ] = { ...builderVersion, status: WorkflowVersionStatus.DEACTIVATED };
+
+ const workflow = fromWorkflowManifestToUniversalFlatWorkflowOrThrow({
+ manifest: manualDefinition,
+ applicationUniversalIdentifier: APPLICATION_ID,
+ now: '2026-10-27T10:00:00.000Z',
+ logicFunctionIdByUniversalIdentifier: new Map(),
+ existingWorkflow:
+ existing.flatWorkflowMaps.byUniversalIdentifier[WORKFLOW_ID],
+ isWorkspaceCustomApplication: true,
+ });
+ const version = workflow.flatUniversalWorkflowVersion!;
+
+ expect(expand(workflow, existing).workflowVersion).toEqual({
+ flatEntityToCreate: { [version.universalIdentifier]: version },
+ flatEntityToUpdate: {},
+ });
+ });
+});
+
const validate = (version: ReturnType<typeof convert>['version']) => ({
errors: validateApplicationWorkflowVersion({ version }),
});
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
index e3976bfd0db..a685ba146c9 100644
--- 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
@@ -1,9 +1,9 @@
-import {
- getWorkflowCommandMenuItemUniversalIdentifier,
- getWorkflowVersionUniversalIdentifier,
-} from 'twenty-shared/application';
-import { isDefined } from 'twenty-shared/utils';
+import { getWorkflowCommandMenuItemUniversalIdentifier } from 'twenty-shared/application';
+import { fromArrayToUniqueKeyRecord, isDefined } from 'twenty-shared/utils';
+import { v4 } from 'uuid';
+import { WorkflowVersionStatus } from 'src/engine/core-modules/workflow/entities/workflow-version.entity';
+import { type FlatWorkflowVersion } from 'src/engine/metadata-modules/flat-workflow-version/types/flat-workflow-version.type';
import { type BuildSideEffectsArgs } from 'src/engine/metadata-modules/metadata-side-effect/interfaces/base-metadata-side-effect-handler.service';
import { type MetadataSideEffectOperationsByMetadataName } from 'src/engine/metadata-modules/metadata-side-effect/types/metadata-side-effect-operations-by-metadata-name.type';
import { type MetadataSideEffectResult } from 'src/engine/metadata-modules/metadata-side-effect/types/metadata-side-effect-result.type';
@@ -19,80 +19,159 @@ export const buildWorkflowVersionSideEffects = ({
return { status: 'noop' };
}
- const universalIdentifier = getWorkflowVersionUniversalIdentifier({
- applicationUniversalIdentifier: flatEntity.applicationUniversalIdentifier,
- workflowUniversalIdentifier: flatEntity.universalIdentifier,
- });
-
+ const { universalIdentifier } = version;
+ const workflowVersions = Object.values(
+ relatedFlatEntityMaps.flatWorkflowVersionMaps.byUniversalIdentifier,
+ )
+ .filter(isDefined)
+ .filter(({ coreWorkflowId }) => coreWorkflowId === version.coreWorkflowId);
const existingVersion =
relatedFlatEntityMaps.flatWorkflowVersionMaps.byUniversalIdentifier[
universalIdentifier
];
+ const archivedVersions = archiveOtherActiveVersions({
+ versionStatus: version.status,
+ universalIdentifier,
+ workflowVersions,
+ });
+ const archivedVersionRecord = fromArrayToUniqueKeyRecord({
+ array: archivedVersions,
+ uniqueKey: 'universalIdentifier',
+ });
return {
status: 'success',
operations: {
- workflowVersion: {
- [isDefined(existingVersion)
- ? 'flatEntityToUpdate'
- : 'flatEntityToCreate']: {
- [universalIdentifier]: { ...version, universalIdentifier },
- },
- },
+ workflowVersion: isDefined(existingVersion)
+ ? {
+ flatEntityToUpdate: {
+ ...archivedVersionRecord,
+ [universalIdentifier]: version,
+ },
+ }
+ : {
+ flatEntityToCreate: { [universalIdentifier]: version },
+ flatEntityToUpdate: archivedVersionRecord,
+ },
...buildWorkflowCommandMenuItemOperations({
flatEntity,
- relatedFlatEntityMaps,
+ flatCommandMenuItemMaps: relatedFlatEntityMaps.flatCommandMenuItemMaps,
+ workflowVersionIds: new Set(workflowVersions.map(({ id }) => id)),
}),
},
};
};
+const archiveOtherActiveVersions = ({
+ versionStatus,
+ universalIdentifier,
+ workflowVersions,
+}: {
+ versionStatus: WorkflowVersionStatus;
+ universalIdentifier: string;
+ workflowVersions: FlatWorkflowVersion[];
+}): FlatWorkflowVersion[] => {
+ if (versionStatus !== WorkflowVersionStatus.ACTIVE) {
+ return [];
+ }
+
+ return workflowVersions
+ .filter(
+ (workflowVersion) =>
+ workflowVersion.status === WorkflowVersionStatus.ACTIVE &&
+ workflowVersion.universalIdentifier !== universalIdentifier,
+ )
+ .map((workflowVersion) => ({
+ ...workflowVersion,
+ status: WorkflowVersionStatus.ARCHIVED,
+ }));
+};
+
+// A command's version binding cannot be updated, so commands bound to other versions are replaced
const buildWorkflowCommandMenuItemOperations = ({
flatEntity,
- relatedFlatEntityMaps,
+ flatCommandMenuItemMaps,
+ workflowVersionIds,
}: {
flatEntity: UniversalFlatWorkflow;
- relatedFlatEntityMaps: BuildSideEffectsArgs<'workflow'>['relatedFlatEntityMaps'];
-}): MetadataSideEffectOperationsByMetadataName => {
+ workflowVersionIds: Set<string>;
+} & Pick<
+ BuildSideEffectsArgs<'workflow'>['relatedFlatEntityMaps'],
+ 'flatCommandMenuItemMaps'
+>): MetadataSideEffectOperationsByMetadataName => {
const commandMenuItem = flatEntity.flatUniversalCommandMenuItem;
- const universalIdentifier = getWorkflowCommandMenuItemUniversalIdentifier({
- applicationUniversalIdentifier: flatEntity.applicationUniversalIdentifier,
- workflowUniversalIdentifier: flatEntity.universalIdentifier,
+ const managedUniversalIdentifier =
+ getWorkflowCommandMenuItemUniversalIdentifier({
+ applicationUniversalIdentifier: flatEntity.applicationUniversalIdentifier,
+ workflowUniversalIdentifier: flatEntity.universalIdentifier,
+ });
+ const existingCommandMenuItems = Object.values(
+ flatCommandMenuItemMaps.byUniversalIdentifier,
+ )
+ .filter(isDefined)
+ .filter(
+ ({ universalIdentifier, coreWorkflowVersionId }) =>
+ universalIdentifier === managedUniversalIdentifier ||
+ (isDefined(coreWorkflowVersionId) &&
+ workflowVersionIds.has(coreWorkflowVersionId)),
+ );
+ const keptCommandMenuItem = isDefined(commandMenuItem)
+ ? existingCommandMenuItems.find(
+ ({ coreWorkflowVersionId }) =>
+ coreWorkflowVersionId === commandMenuItem.coreWorkflowVersionId,
+ )
+ : undefined;
+ const deletedCommandMenuItems = existingCommandMenuItems.filter(
+ (existingCommandMenuItem) =>
+ existingCommandMenuItem !== keptCommandMenuItem,
+ );
+ const flatEntityToDelete = fromArrayToUniqueKeyRecord({
+ array: deletedCommandMenuItems,
+ uniqueKey: 'universalIdentifier',
});
- const existingCommandMenuItem =
- relatedFlatEntityMaps.flatCommandMenuItemMaps.byUniversalIdentifier[
- universalIdentifier
- ];
if (!isDefined(commandMenuItem)) {
- return isDefined(existingCommandMenuItem)
- ? {
- commandMenuItem: {
- flatEntityToDelete: {
- [universalIdentifier]: existingCommandMenuItem,
- },
- },
- }
+ return deletedCommandMenuItems.length > 0
+ ? { commandMenuItem: { flatEntityToDelete } }
: {};
}
- if (!isDefined(existingCommandMenuItem)) {
+ if (isDefined(keptCommandMenuItem)) {
return {
commandMenuItem: {
- flatEntityToCreate: { [universalIdentifier]: commandMenuItem },
+ flatEntityToDelete,
+ flatEntityToUpdate: {
+ [keptCommandMenuItem.universalIdentifier]: {
+ ...commandMenuItem,
+ universalIdentifier: keptCommandMenuItem.universalIdentifier,
+ position: keptCommandMenuItem.position,
+ isActive: keptCommandMenuItem.isActive,
+ universalOverrides: keptCommandMenuItem.universalOverrides,
+ isSystemSideEffect: keptCommandMenuItem.isSystemSideEffect,
+ workflowVersionId: keptCommandMenuItem.workflowVersionId,
+ createdAt: keptCommandMenuItem.createdAt,
+ },
+ },
},
};
}
+ // A deleted command and its replacement cannot share an identifier within one migration
+ const createdUniversalIdentifier = isDefined(
+ flatCommandMenuItemMaps.byUniversalIdentifier[
+ commandMenuItem.universalIdentifier
+ ],
+ )
+ ? v4()
+ : commandMenuItem.universalIdentifier;
+
return {
commandMenuItem: {
- flatEntityToUpdate: {
- [universalIdentifier]: {
+ flatEntityToDelete,
+ flatEntityToCreate: {
+ [createdUniversalIdentifier]: {
...commandMenuItem,
- position: existingCommandMenuItem.position,
- isActive: existingCommandMenuItem.isActive,
- universalOverrides: existingCommandMenuItem.universalOverrides,
- createdAt: existingCommandMenuItem.createdAt,
+ universalIdentifier: createdUniversalIdentifier,
},
},
},
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/__tests__/compute-ordered-migration-actions.util.spec.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/__tests__/compute-ordered-migration-actions.util.spec.ts
index 29207b6f469..bab61dcf4f4 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/__tests__/compute-ordered-migration-actions.util.spec.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/__tests__/compute-ordered-migration-actions.util.spec.ts
@@ -20,6 +20,10 @@ import {
type UniversalUpdateSettingsMenuItemAction,
} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/settings-menu-item/types/workspace-migration-settings-menu-item-action.type';
import { type UniversalCreateViewSortAction } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/view-sort/types/workspace-migration-view-sort-action.type';
+import {
+ type UniversalCreateWorkflowVersionAction,
+ type UniversalUpdateWorkflowVersionAction,
+} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/workflow-version/types/workspace-migration-workflow-version-action.type';
describe('computeOrderedMigrationActions', () => {
it('should remove a replaced view sort before creating its replacement', () => {
@@ -145,6 +149,32 @@ describe('computeOrderedMigrationActions', () => {
);
});
+ it('should archive the active workflow version before creating the one that replaces it', () => {
+ const archiveAction = {
+ type: 'update',
+ metadataName: 'workflowVersion',
+ universalIdentifier: 'published-version',
+ update: { status: 'ARCHIVED' },
+ } as unknown as UniversalUpdateWorkflowVersionAction;
+ const publishAction = {
+ type: 'create',
+ metadataName: 'workflowVersion',
+ flatEntity: { universalIdentifier: 'new-version', status: 'ACTIVE' },
+ } as unknown as UniversalCreateWorkflowVersionAction;
+ const orchestratorActionsReport = createEmptyOrchestratorActionsReport();
+
+ orchestratorActionsReport.workflowVersion.create.push(publishAction);
+ orchestratorActionsReport.workflowVersion.update.push(archiveAction);
+
+ const orderedActions = computeOrderedMigrationActions(
+ orchestratorActionsReport,
+ );
+
+ expect(orderedActions.indexOf(archiveAction)).toBeLessThan(
+ orderedActions.indexOf(publishAction),
+ );
+ });
+
it('should run pageLayout creates before pageLayoutTab creates', () => {
const pageLayoutCreateAction = {
type: 'create',
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/compute-ordered-migration-actions.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/compute-ordered-migration-actions.util.ts
index 7a494819c40..230538bd53d 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/compute-ordered-migration-actions.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/compute-ordered-migration-actions.util.ts
@@ -46,8 +46,9 @@ export const computeOrderedMigrationActions = (
...aggregatedOrchestratorActionsReport.workflow.delete,
...aggregatedOrchestratorActionsReport.workflow.create,
...aggregatedOrchestratorActionsReport.workflow.update,
- ...aggregatedOrchestratorActionsReport.workflowVersion.create,
+ // At most one version per workflow is ACTIVE (unique index), so the published one is archived before its successor is created
...aggregatedOrchestratorActionsReport.workflowVersion.update,
+ ...aggregatedOrchestratorActionsReport.workflowVersion.create,
...aggregatedOrchestratorActionsReport.logicFunction.delete,
...aggregatedOrchestratorActionsReport.logicFunction.create,
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.ts
index bf951ec72ae..366d069cd30 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.ts
@@ -1,3 +1,17 @@
+import {
+ activateCoreWorkflowVersion,
+ createCoreWorkflow,
+ createCoreWorkflowVersionStep,
+ deactivateCoreWorkflowVersion,
+ deleteCoreWorkflows,
+ runCoreWorkflowVersion,
+ updateCoreWorkflowVersionStep,
+ updateCoreWorkflowVersionTrigger,
+} from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';
+import {
+ destroyWorkflowRun,
+ getWorkflowRun,
+} from 'test/integration/graphql/suites/workflow/utils/workflow-run-test.util';
import { findManyApplications } from 'test/integration/graphql/utils/find-many-applications.util';
import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
import { buildDefaultObjectManifest } from 'test/integration/metadata/suites/application/utils/build-default-object-manifest.util';
@@ -16,6 +30,7 @@ import { createOneViewFilter } from 'test/integration/metadata/suites/view-filte
import { destroyOneViewFilter } from 'test/integration/metadata/suites/view-filter/utils/destroy-one-view-filter.util';
import { createOneView } from 'test/integration/metadata/suites/view/utils/create-one-view.util';
import { destroyOneView } from 'test/integration/metadata/suites/view/utils/destroy-one-view.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';
import {
type AgentManifest,
@@ -33,6 +48,7 @@ import {
getSystemViewUniversalIdentifier,
getWorkflowCommandMenuItemUniversalIdentifier,
getWorkflowVersionUniversalIdentifier,
+ type Manifest,
type NavigationMenuItemManifest,
type ObjectManifest,
type PageLayoutManifest,
@@ -71,7 +87,11 @@ import {
import { isDefined } from 'twenty-shared/utils';
import { version as getUuidVersion, v4 } from 'uuid';
+import { type ApplicationManifestMigrationService } from 'src/engine/core-modules/application/application-manifest/application-manifest-migration.service';
+import { fromWorkflowManifestToUniversalFlatWorkflowOrThrow } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util';
+import { type ApplicationService } from 'src/engine/core-modules/application/application.service';
import { WORKSPACE_CUSTOM_APPLICATION_NAME } from 'src/engine/core-modules/application/constants/workspace-custom-application.constant';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
import { ApplicationExportCoverageStatus } from 'src/engine/core-modules/application/enums/application-export-coverage-status.enum';
import { fromObjectManifestToUniversalFlatObjectMetadata } from 'src/engine/core-modules/application/application-manifest/converters/from-object-manifest-to-universal-flat-object-metadata.util';
import { buildSearchVectorFlatFieldMetadataForCustomObject } from 'src/engine/metadata-modules/object-metadata/utils/build-search-vector-flat-field-metadata-for-custom-object.util';
@@ -1818,6 +1838,263 @@ describe('Application export - workflows', () => {
}, 60000);
});
+const findWorkspaceCustomFlatApplication = async () =>
+ (
+ await getAppProviderByClassName<ApplicationService>(
+ 'ApplicationService',
+ ).findWorkspaceTwentyStandardAndCustomApplicationOrThrow({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ })
+ ).workspaceCustomFlatApplication;
+
+// The seeded workspace lacks the dependency files a full sync of its custom application needs
+const applyWorkspaceCustomApplicationManifest = async (manifest: Manifest) =>
+ (
+ await getAppProviderByClassName<ApplicationManifestMigrationService>(
+ 'ApplicationManifestMigrationService',
+ ).syncMetadataFromManifest({
+ manifest,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ ownerFlatApplication: await findWorkspaceCustomFlatApplication(),
+ inferDeletionFromMissingEntities: false,
+ })
+ ).workspaceMigration.actions;
+
+describe('Application export - workflows built in the workflow builder', () => {
+ const workflowName = 'Notify sales from the builder';
+ let coreWorkflowId: string;
+ let builderVersionId: string;
+ let workflowUniversalIdentifier: string;
+ let workflowRunId: string | undefined;
+
+ const buildManifest = (url: string): WorkflowManifest => ({
+ universalIdentifier: workflowUniversalIdentifier,
+ name: workflowName,
+ version: {
+ trigger: {
+ universalIdentifier: workflowNodeIdentifier(40),
+ type: 'MANUAL',
+ nextStepIds: [workflowNodeIdentifier(41)],
+ settings: { availability: { type: 'GLOBAL' }, isPinned: true },
+ },
+ steps: [
+ {
+ universalIdentifier: workflowNodeIdentifier(41),
+ name: 'Notify sales',
+ type: 'HTTP_REQUEST',
+ nextStepIds: [],
+ input: { method: 'POST', url },
+ },
+ ],
+ },
+ });
+
+ const findWorkflowVersions = async () => {
+ const versions: {
+ id: string;
+ status: string;
+ steps: { settings: { input: { url: string } } }[];
+ }[] = await global.testDataSource.query(
+ `SELECT id, status, steps FROM core."workflowVersion" WHERE "coreWorkflowId" = $1`,
+ [coreWorkflowId],
+ );
+
+ return versions;
+ };
+
+ const exportWorkspaceCustomApplication = async () => {
+ const { universalIdentifier } = await findWorkspaceCustomFlatApplication();
+ const { data, errors } = await exportApplication({
+ universalIdentifier,
+ expectToFail: false,
+ });
+
+ expect(errors).toBeUndefined();
+
+ return data.exportApplication;
+ };
+
+ beforeAll(async () => {
+ const customFlatApplication = await findWorkspaceCustomFlatApplication();
+ const createdWorkflow = await createCoreWorkflow({ name: workflowName });
+
+ coreWorkflowId = createdWorkflow.coreWorkflowId;
+ builderVersionId = createdWorkflow.coreWorkflowVersionId;
+
+ const [{ universalIdentifier }] = await global.testDataSource.query(
+ `SELECT "universalIdentifier" FROM core.workflow WHERE id = $1`,
+ [coreWorkflowId],
+ );
+
+ workflowUniversalIdentifier = universalIdentifier;
+
+ // The builder stores whatever trigger and steps it is sent, so it is sent exactly what a manifest produces
+ const { triggers, steps } =
+ fromWorkflowManifestToUniversalFlatWorkflowOrThrow({
+ manifest: buildManifest('http://localhost:1/before'),
+ applicationUniversalIdentifier:
+ customFlatApplication.universalIdentifier,
+ now: new Date().toISOString(),
+ logicFunctionIdByUniversalIdentifier: new Map(),
+ }).flatUniversalWorkflowVersion!;
+ const [trigger] = triggers!;
+ const [step] = steps!;
+
+ await updateCoreWorkflowVersionTrigger({
+ coreWorkflowVersionId: builderVersionId,
+ trigger: { ...trigger, nextStepIds: [] },
+ });
+ await createCoreWorkflowVersionStep({
+ coreWorkflowVersionId: builderVersionId,
+ stepType: 'HTTP_REQUEST',
+ id: step.id,
+ });
+ await updateCoreWorkflowVersionTrigger({
+ coreWorkflowVersionId: builderVersionId,
+ trigger,
+ });
+ await updateCoreWorkflowVersionStep({
+ coreWorkflowVersionId: builderVersionId,
+ step,
+ });
+ await activateCoreWorkflowVersion({
+ coreWorkflowVersionId: builderVersionId,
+ });
+ }, 60000);
+
+ afterAll(async () => {
+ if (isDefined(workflowRunId)) {
+ await destroyWorkflowRun(workflowRunId);
+ }
+ await deleteCoreWorkflows({ coreWorkflowIds: [coreWorkflowId] });
+ });
+
+ it('exports the active version and round-trips it without any action', async () => {
+ const { manifest, coverage } = await exportWorkspaceCustomApplication();
+
+ expect(
+ coverage.find(
+ (entry) => entry.universalIdentifier === workflowUniversalIdentifier,
+ )?.status,
+ ).toBe(ApplicationExportCoverageStatus.EXPORTED);
+ expect(
+ manifest.workflows?.find(
+ (workflow) =>
+ workflow.universalIdentifier === workflowUniversalIdentifier,
+ ),
+ ).toEqual(buildManifest('http://localhost:1/before'));
+
+ const dryRun = await syncApplication({
+ manifest,
+ dryRun: true,
+ inferDeletionFromMissingEntities: false,
+ expectToFail: false,
+ });
+
+ expect(dryRun.errors).toBeUndefined();
+ expect(dryRun.data.syncApplication.actions).toEqual([]);
+ }, 60000);
+
+ it('publishes a changed definition like the builder and keeps the run history', async () => {
+ workflowRunId = await runCoreWorkflowVersion({
+ coreWorkflowVersionId: builderVersionId,
+ });
+
+ const { manifest } = await exportWorkspaceCustomApplication();
+ const changedManifest: Manifest = {
+ ...manifest,
+ workflows: [buildManifest('http://localhost:1/after')],
+ };
+
+ await applyWorkspaceCustomApplicationManifest(changedManifest);
+
+ const versions = await findWorkflowVersions();
+ const activeVersions = versions.filter(({ status }) => status === 'ACTIVE');
+
+ expect(activeVersions).toHaveLength(1);
+ expect(activeVersions[0].id).not.toBe(builderVersionId);
+ expect(activeVersions[0].steps[0].settings.input.url).toBe(
+ 'http://localhost:1/after',
+ );
+ expect(versions.find(({ id }) => id === builderVersionId)).toMatchObject({
+ status: 'ARCHIVED',
+ steps: [
+ expect.objectContaining({
+ settings: expect.objectContaining({
+ input: expect.objectContaining({
+ url: 'http://localhost:1/before',
+ }),
+ }),
+ }),
+ ],
+ });
+ expect((await getWorkflowRun(workflowRunId))?.coreWorkflowVersionId).toBe(
+ builderVersionId,
+ );
+
+ const [workflow] = await global.testDataSource.query(
+ `SELECT "lastPublishedCoreWorkflowVersionId", "createdByUserWorkspaceId" FROM core.workflow WHERE id = $1`,
+ [coreWorkflowId],
+ );
+
+ expect(workflow.lastPublishedCoreWorkflowVersionId).toBe(
+ activeVersions[0].id,
+ );
+ expect(workflow.createdByUserWorkspaceId).not.toBeNull();
+
+ const commandMenuItems = await global.testDataSource.query(
+ `SELECT "coreWorkflowVersionId" FROM core."commandMenuItem" WHERE "coreWorkflowVersionId" = ANY($1)`,
+ [versions.map(({ id }) => id)],
+ );
+
+ expect(commandMenuItems).toEqual([
+ { coreWorkflowVersionId: activeVersions[0].id },
+ ]);
+
+ expect(
+ await applyWorkspaceCustomApplicationManifest(changedManifest),
+ ).toEqual([]);
+ expect(await findWorkflowVersions()).toHaveLength(versions.length);
+
+ const { manifest: exportedAfterPublish } =
+ await exportWorkspaceCustomApplication();
+
+ expect(
+ exportedAfterPublish.workflows?.find(
+ (workflow) =>
+ workflow.universalIdentifier === workflowUniversalIdentifier,
+ ),
+ ).toEqual(buildManifest('http://localhost:1/after'));
+ }, 60000);
+
+ it('shows the published command again after a deactivation and reactivation', async () => {
+ const [activeVersion] = (await findWorkflowVersions()).filter(
+ ({ status }) => status === 'ACTIVE',
+ );
+
+ await deactivateCoreWorkflowVersion({
+ coreWorkflowVersionId: activeVersion.id,
+ });
+ await activateCoreWorkflowVersion({
+ coreWorkflowVersionId: activeVersion.id,
+ });
+
+ const commandMenuItems: {
+ isActive: boolean;
+ overrides: Record<string, { isActive?: boolean }> | null;
+ }[] = await global.testDataSource.query(
+ `SELECT "isActive", overrides FROM core."commandMenuItem" WHERE "coreWorkflowVersionId" = $1`,
+ [activeVersion.id],
+ );
+
+ expect(commandMenuItems).toHaveLength(1);
+ expect(commandMenuItems[0].isActive).toBe(true);
+ expect(
+ Object.values(commandMenuItems[0].overrides ?? {}),
+ ).not.toContainEqual(expect.objectContaining({ isActive: false }));
+ }, 60000);
+});
+
const AI_TEST_APP_ID = '7e3d1c2b-0300-4a7b-8c9d-0e1f2a3b4c5d';
const AI_TEST_ROLE_ID = '7e3d1c2b-0301-4a7b-8c9d-0e1f2a3b4c5d';
const TRIAGE_AGENT_ID = '7e3d1c2b-0302-4a7b-8c9d-0e1f2a3b4c5d';