The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Export application workflows for twenty app pull (#28936)
Félix Malfait7d3c4e6645c0
diff --git a/packages/twenty-cli/docs/commands.md b/packages/twenty-cli/docs/commands.mdindex a0ffd83552a..f915dca05ac 100644--- a/packages/twenty-cli/docs/commands.md+++ b/packages/twenty-cli/docs/commands.md@@ -418,7 +418,7 @@ twenty app pull --universal-identifier <uuid> --verbose`app pull` reads the app's definition and exports its workspace metadata into the existing project. It uses the selected connection and the server's `APPLICATIONS` permission; the server decides which apps this workspace can export. It does not register an app or change the workspace. When a project has no application definition, provide `--universal-identifier`. A project declaring a different app is refused before writing.-The project must have `twenty-sdk` installed, version `>=1.23.0`, with its public `twenty-sdk/define` and `twenty-sdk/front-component` exports. Pull also checks that the SDK provides the authoring APIs required by the generated files. Missing APIs fail with `SDK_SOURCE_UNSUPPORTED`; install a compatible version (2.40.0 or later). Pull does not require a project TypeScript compiler. Run `twenty app typecheck` afterwards to check the generated definitions against your installed SDK.+The project must have `twenty-sdk` installed, version `>=1.23.0`, with its public `twenty-sdk/define` and `twenty-sdk/front-component` exports. Pull also checks that the SDK provides the authoring APIs required by the generated files. Missing APIs fail with `SDK_SOURCE_UNSUPPORTED`; install a compatible version (2.50.0 or later). Pull does not require a project TypeScript compiler. Run `twenty app typecheck` afterwards to check the generated definitions against your installed SDK.Pull compares workspace metadata and local definitions using a baseline savedby apply or a previous pull in `.twenty/cli/pull-base.json`. The baseline belongs@@ -432,7 +432,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. 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. 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 appdiff --git a/packages/twenty-cli/src/app/pull/README.md b/packages/twenty-cli/src/app/pull/README.mdindex b1169bbb60b..8e4dad74c4e 100644--- a/packages/twenty-cli/src/app/pull/README.md+++ b/packages/twenty-cli/src/app/pull/README.md@@ -23,6 +23,8 @@ See the [app tooling overview](../README.md) for package boundaries.Translation string extraction uses the CLI's TypeScript parser. Traversal, static-string rules, whitespace normalization and deduplication are checked against the SDK reference by parity tests. It does not depend on ts-morph or load parser tooling for help and command discovery.+Workflows arrive in `manifest.workflows` and are written as `defineWorkflow` files. Their filter operands and form field types use SDK enums; filter group logical operators stay string literals, which every SDK with `defineWorkflow` accepts. A workflow the server cannot express as a definition is reported as `UNSUPPORTED` coverage, so its local file is kept.+Pull accepts metadata exports with `files: []` and refuses nonempty source/dependency-file exports. It does not restore package files, generate the typed client or write logic-function/front-component source. Export responses have a 16 MiB cap. Pull does not modify the workspace.Tests cover writers, planning and reconciliation. Command tests build the actual Vite worker, exercise an authoring-only SDK, local mock HTTP, credentials/output isolation, SDK export refusal and forced termination after the first destination write. The repository SDK tests cover canonical generated definitions, nested coverage, translation preservation, target mismatch, overwrite reporting and rollback.diff --git a/packages/twenty-cli/src/app/pull/__tests__/build-pull-entities.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/build-pull-entities.spec.tsindex ed4cedfcacd..2e90cb99184 100644--- a/packages/twenty-cli/src/app/pull/__tests__/build-pull-entities.spec.ts+++ b/packages/twenty-cli/src/app/pull/__tests__/build-pull-entities.spec.ts@@ -6,6 +6,7 @@ import {ROLE_ENUM_BINDINGS,VIEW_ENUM_BINDINGS,VIEW_FIELD_ENUM_BINDINGS,+ WORKFLOW_ENUM_BINDINGS,} from '@/app/pull/write-define-file';import {getFieldPermissionUniversalIdentifier,@@ -19,6 +20,7 @@ import {type StandaloneViewFieldManifest,SYSTEM_VIEW_KEYS,type ViewManifest,+ type WorkflowManifest,} from 'twenty-shared/application';import {STANDARD_OBJECT_FIELDS,@@ -57,6 +59,9 @@ const SUPPORT_ROLE_UID = '30303030-3030-4303-8303-303030303030';const AUDITOR_ROLE_UID = '40404040-4040-4404-8404-404040404040';const EXPORT_PETS_FLAG_UID = '50505050-5050-4505-8505-505050505050';const LEGACY_OBJECT_PERMISSION_UID = '60606060-6060-4606-8606-606060606060';+const WORKFLOW_UID = '70707070-7070-4707-8707-707070707070';+const WORKFLOW_TRIGGER_UID = '80808080-8080-4808-8808-808080808080';+const WORKFLOW_STEP_UID = '90909090-9090-4909-8909-909090909090';const APPLICATION_WITH_SUPPORT_DEFAULT_ROLE = {universalIdentifier: APP_UID,@@ -199,6 +204,28 @@ const buildNavigationMenuItemManifest = (...overrides,});+const WORKFLOW_MANIFEST: WorkflowManifest = {+ universalIdentifier: WORKFLOW_UID,+ name: 'Welcome new pets',+ version: {+ trigger: {+ universalIdentifier: WORKFLOW_TRIGGER_UID,+ type: 'DATABASE_EVENT',+ nextStepIds: [WORKFLOW_STEP_UID],+ settings: { objectUniversalIdentifier: PET_UID, action: 'created' },+ },+ steps: [+ {+ universalIdentifier: WORKFLOW_STEP_UID,+ name: 'Done',+ type: 'EMPTY',+ nextStepIds: [],+ input: {},+ },+ ],+ },+};+describe('buildPullEntities', () => {it('should strip the checksums the build recomputes from the application config', () => {const { entities } = buildPullEntities(buildManifest());@@ -925,6 +952,35 @@ describe('buildPullEntities', () => {expect(JSON.stringify(widget?.config)).not.toContain('__typename');});+ it('should write a workflow verbatim into src/workflows with the workflow enum bindings, named after the workflow', () => {+ const { entities, skipped } = buildPullEntities(+ buildManifest({ workflows: [WORKFLOW_MANIFEST] }),+ );+ const workflow = entities.find((entity) => entity.kind === 'workflow');++ expect(skipped).toEqual([]);+ expect(workflow).toMatchObject({+ universalIdentifier: WORKFLOW_UID,+ definer: 'defineWorkflow',+ config: WORKFLOW_MANIFEST,+ enumBindings: WORKFLOW_ENUM_BINDINGS,+ parentName: null,+ });+ expect(+ `${workflow?.defaultFolder}/${workflow?.fileBaseName}${workflow?.fileSuffix}`,+ ).toBe('src/workflows/welcome-new-pets.workflow.ts');+ });++ it('should name a workflow whose name has no kebab-case form after its identifier prefix', () => {+ const { entities } = buildPullEntities(+ buildManifest({ workflows: [{ ...WORKFLOW_MANIFEST, name: '!!!' }] }),+ );++ expect(+ entities.find((entity) => entity.kind === 'workflow')?.fileBaseName,+ ).toBe('70707070');+ });+it('should build a manifest that has no views, view fields, page layouts and page layout tabs properties without producing their entities', () => {const {views: _views,diff --git a/packages/twenty-cli/src/app/pull/__tests__/pull-application.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/pull-application.spec.tsindex c45228ad478..6019289254d 100644--- a/packages/twenty-cli/src/app/pull/__tests__/pull-application.spec.ts+++ b/packages/twenty-cli/src/app/pull/__tests__/pull-application.spec.ts@@ -34,6 +34,9 @@ const OTHER_IDENTIFIER = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee';const INDEX_IDENTIFIER = 'ffffffff-ffff-4fff-8fff-ffffffffffff';const STANDALONE_FIELD_IDENTIFIER = 'abababab-abab-4aba-8aba-abababababab';const STANDALONE_FIELD_PATH = 'src/fields/rating.ts';+const WORKFLOW_IDENTIFIER = 'acacacac-acac-4aca-8aca-acacacacacac';+const WORKFLOW_TRIGGER_IDENTIFIER = 'adadadad-adad-4ada-8ada-adadadadadad';+const WORKFLOW_STEP_IDENTIFIER = 'aeaeaeae-aeae-4aea-8aea-aeaeaeaeaeae';const TARGET: AppPullTarget = {apiUrl: 'https://example.test',workspaceId: WORKSPACE_IDENTIFIER,@@ -706,6 +709,108 @@ export default defineField({expect(await read(applicationPath)).toContain('Changed remotely');});+ it('writes workflows, keeps them while unchanged or unsupported and removes confirmed remote deletions', async () => {+ const workflowPath = 'src/workflows/greet-new-pets.workflow.ts';+ const workflow = {+ universalIdentifier: WORKFLOW_IDENTIFIER,+ name: 'Greet new pets',+ version: {+ trigger: {+ universalIdentifier: WORKFLOW_TRIGGER_IDENTIFIER,+ type: 'DATABASE_EVENT',+ nextStepIds: [WORKFLOW_STEP_IDENTIFIER],+ settings: {+ action: 'created',+ filter: {+ stepFilterGroups: [{ id: 'group', logicalOperator: 'AND' }],+ stepFilters: [+ {+ id: 'filter',+ operand: 'IS_NOT_EMPTY',+ stepFilterGroupId: 'group',+ stepOutputKey: '{{trigger.properties.after.name}}',+ type: 'TEXT',+ value: '',+ },+ ],+ },+ objectUniversalIdentifier: OBJECT_IDENTIFIER,+ },+ },+ steps: [+ {+ universalIdentifier: WORKFLOW_STEP_IDENTIFIER,+ name: 'Greet',+ type: 'HTTP_REQUEST',+ nextStepIds: [],+ input: { method: 'GET', url: 'https://example.test/greet' },+ },+ ],+ },+ };+ const withWorkflow = (value: typeof workflow) => {+ const exported = createExport();++ return {+ ...exported,+ manifest: { ...exported.manifest, workflows: [value] },+ };+ };++ const created = requireSuccess(await pull(withWorkflow(workflow)));+ expect(created.writes).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ relativePath: workflowPath,+ kind: 'workflow',+ }),+ ]),+ );+ expect(await read(workflowPath)).toContain(+ 'operand: ViewFilterOperand.IS_NOT_EMPTY,',+ );++ const localEdit = (await read(workflowPath)).replace(+ "name: 'Greet',",+ "name: 'Greet',\n",+ );+ await writeFile(join(appPath, workflowPath), localEdit);+ expect(requireSuccess(await pull(withWorkflow(workflow))).writes).toEqual(+ [],+ );+ expect(await read(workflowPath)).toBe(localEdit);++ const renamed = { ...workflow, name: 'Welcome new pets' };+ const changed = requireSuccess(await pull(withWorkflow(renamed)));+ expect(changed.writes).toEqual([+ expect.objectContaining({+ relativePath: workflowPath,+ isRegeneration: true,+ }),+ ]);+ expect(await read(workflowPath)).toContain("name: 'Welcome new pets',");++ const unsupported = createExport({+ coverage: [+ {+ metadataName: 'workflow',+ universalIdentifier: WORKFLOW_IDENTIFIER,+ status: 'UNSUPPORTED',+ reason: 'workflow changed in the workflow builder',+ },+ ],+ });+ const kept = requireSuccess(await pull(unsupported));+ expect(kept.deletions).toEqual([]);+ expect(await read(workflowPath)).toContain("name: 'Welcome new pets',");++ const removed = requireSuccess(await pull(createExport()));+ expect(removed.deletions).toEqual([+ { universalIdentifier: WORKFLOW_IDENTIFIER, relativePath: workflowPath },+ ]);+ await expect(read(workflowPath)).rejects.toMatchObject({ code: 'ENOENT' });+ });+it('retains a covered whole-file base until its remote deletion is confirmed', async () => {requireSuccess(await pull());const partialExport = createExport({diff --git a/packages/twenty-cli/src/app/pull/__tests__/write-define-file.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/write-define-file.spec.tsindex 998c27e5d7b..04c3439bf14 100644--- a/packages/twenty-cli/src/app/pull/__tests__/write-define-file.spec.ts+++ b/packages/twenty-cli/src/app/pull/__tests__/write-define-file.spec.ts@@ -8,6 +8,7 @@ import {ROLE_ENUM_BINDINGS,VIEW_ENUM_BINDINGS,VIEW_FIELD_ENUM_BINDINGS,+ WORKFLOW_ENUM_BINDINGS,writeDefineFile,} from '@/app/pull/write-define-file';import { SystemPermissionFlag } from 'twenty-shared/constants';@@ -553,4 +554,97 @@ describe('writeDefineFile', () => {'});\n',);});++ it('should write workflow filter operands and form field types as enum members, keeping logical operators and record pickers literal', () => {+ const stepFilters = {+ stepFilterGroups: [{ id: 'group', logicalOperator: 'AND' }],+ stepFilters: [+ {+ id: 'filter',+ type: 'TEXT',+ stepOutputKey: '{{trigger.properties.after.status}}',+ operand: 'IS',+ value: 'open',+ stepFilterGroupId: 'group',+ },+ ],+ };+ const { content: file, requiredSdkExports } = writeDefineFile({+ definer: 'defineWorkflow',+ config: {+ universalIdentifier: 'workflow-uid',+ name: 'Triage',+ version: {+ trigger: {+ universalIdentifier: 'trigger-uid',+ type: 'DATABASE_EVENT',+ nextStepIds: ['find-uid'],+ settings: {+ action: 'updated',+ filter: stepFilters,+ objectUniversalIdentifier: 'object-uid',+ },+ },+ steps: [+ {+ universalIdentifier: 'find-uid',+ name: 'Find',+ type: 'FIND_RECORDS',+ nextStepIds: ['filter-uid'],+ input: {+ filter: {+ recordFilterGroups: [{ id: 'root', logicalOperator: 'OR' }],+ recordFilters: [+ {+ fieldMetadataUniversalIdentifier: 'field-uid',+ operand: 'IS_NOT_EMPTY',+ },+ ],+ },+ objectUniversalIdentifier: 'object-uid',+ },+ },+ {+ universalIdentifier: 'filter-uid',+ name: 'Filter',+ type: 'FILTER',+ nextStepIds: ['form-uid'],+ input: stepFilters,+ },+ {+ universalIdentifier: 'form-uid',+ name: 'Form',+ type: 'FORM',+ nextStepIds: [],+ input: [+ { id: 'name', label: 'Name', name: 'name', type: 'TEXT' },+ {+ id: 'ticket',+ label: 'Ticket',+ name: 'ticket',+ settings: { objectUniversalIdentifier: 'object-uid' },+ type: 'RECORD',+ },+ ],+ },+ ],+ },+ },+ enumBindings: WORKFLOW_ENUM_BINDINGS,+ });++ expect(requiredSdkExports).toEqual([+ 'defineWorkflow',+ 'FieldType',+ 'ViewFilterOperand',+ ]);+ expect(file.match(/operand: ViewFilterOperand\.IS,/g)).toHaveLength(2);+ expect(file).toContain('operand: ViewFilterOperand.IS_NOT_EMPTY,');+ expect(file).toContain("logicalOperator: 'AND',");+ expect(file).toContain("logicalOperator: 'OR',");+ expect(file).toContain('type: FieldType.TEXT,');+ expect(file).toContain("type: 'RECORD',");+ expect(file).toContain("type: 'FIND_RECORDS',");+ expect(file).toContain("type: 'DATABASE_EVENT',");+ });});diff --git a/packages/twenty-cli/src/app/pull/assert-pull-sdk-exports.ts b/packages/twenty-cli/src/app/pull/assert-pull-sdk-exports.tsindex 5de2d047956..558fff7cc72 100644--- a/packages/twenty-cli/src/app/pull/assert-pull-sdk-exports.ts+++ b/packages/twenty-cli/src/app/pull/assert-pull-sdk-exports.ts@@ -32,7 +32,7 @@ export const assertPullSdkExports = ({throw new CliError({code: 'SDK_SOURCE_UNSUPPORTED',message: `The app's twenty-sdk cannot read the generated definitions. Missing exports: ${missingNames.join(', ')}.`,- hint: 'Upgrade the app to a compatible twenty-sdk version (2.40.0 or later).',+ hint: 'Upgrade the app to a compatible twenty-sdk version (2.50.0 or later).',details: { missingNames },});}diff --git a/packages/twenty-cli/src/app/pull/build-pull-entities.ts b/packages/twenty-cli/src/app/pull/build-pull-entities.tsindex f8963e769b7..062e4564c35 100644--- a/packages/twenty-cli/src/app/pull/build-pull-entities.ts+++ b/packages/twenty-cli/src/app/pull/build-pull-entities.ts@@ -9,6 +9,7 @@ import {ROLE_ENUM_BINDINGS,VIEW_ENUM_BINDINGS,VIEW_FIELD_ENUM_BINDINGS,+ WORKFLOW_ENUM_BINDINGS,type EnumBinding,} from '@/app/pull/write-define-file';import {@@ -43,6 +44,7 @@ export const PULL_ENTITY_KINDS = ['pageLayoutTab','navigationMenuItem','pageLayoutWidget',+ 'workflow',] as const;export type PullEntityKind = (typeof PULL_ENTITY_KINDS)[number];@@ -371,5 +373,22 @@ export const buildPullEntities = (});}+ for (const workflowManifest of manifest.workflows ?? []) {+ entities.push({+ kind: 'workflow',+ universalIdentifier: workflowManifest.universalIdentifier,+ definer: 'defineWorkflow',+ config: workflowManifest,+ enumBindings: WORKFLOW_ENUM_BINDINGS,+ defaultFolder: 'src/workflows',+ fileSuffix: '.workflow.ts',+ fileBaseName: toFileBaseName({+ segments: [workflowManifest.name],+ universalIdentifier: workflowManifest.universalIdentifier,+ }),+ parentName: null,+ });+ }+return { entities, skipped };};diff --git a/packages/twenty-cli/src/app/pull/entity-key-by-kind.constant.ts b/packages/twenty-cli/src/app/pull/entity-key-by-kind.constant.tsindex 518af651115..625750629e2 100644--- a/packages/twenty-cli/src/app/pull/entity-key-by-kind.constant.ts+++ b/packages/twenty-cli/src/app/pull/entity-key-by-kind.constant.ts@@ -14,4 +14,5 @@ export const ENTITY_KEY_BY_KIND: Record<PullEntityKind, ManifestEntityKey> = {pageLayoutTab: 'pageLayoutTabs',navigationMenuItem: 'navigationMenuItems',pageLayoutWidget: 'pageLayoutWidgets',+ workflow: 'workflows',};diff --git a/packages/twenty-cli/src/app/pull/write-define-file.ts b/packages/twenty-cli/src/app/pull/write-define-file.tsindex 9c8899bc022..4a0c95b7ef6 100644--- a/packages/twenty-cli/src/app/pull/write-define-file.ts+++ b/packages/twenty-cli/src/app/pull/write-define-file.ts@@ -202,6 +202,47 @@ export const PAGE_LAYOUT_ENUM_BINDINGS: EnumBinding[] = [...buildPageLayoutTabEnumBindings(['tabs', '[]']),];+const STEP_PATH = ['version', 'steps', '[]'];++const buildViewFilterOperandBinding = (path: string[]): EnumBinding => ({+ path,+ symbol: 'ViewFilterOperand',+ members: ViewFilterOperand,+});++// twenty-sdk/define exports no filter group operator enums, so those stay string literals.+export const WORKFLOW_ENUM_BINDINGS: EnumBinding[] = [+ buildViewFilterOperandBinding([+ 'version',+ 'trigger',+ 'settings',+ 'filter',+ 'stepFilters',+ '[]',+ 'operand',+ ]),+ buildViewFilterOperandBinding([+ ...STEP_PATH,+ 'input',+ 'stepFilters',+ '[]',+ 'operand',+ ]),+ buildViewFilterOperandBinding([+ ...STEP_PATH,+ 'input',+ 'filter',+ 'recordFilters',+ '[]',+ 'operand',+ ]),+ {+ path: [...STEP_PATH, 'input', '[]', 'type'],+ symbol: 'FieldType',+ members: FieldMetadataType,+ },+];+const isSamePath = (left: string[], right: string[]): boolean =>left.length === right.length &&left.every((segment, index) => segment === right[index]);diff --git a/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts b/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.tsindex c9362d3a860..b6d8223e9ce 100644--- a/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts+++ b/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts@@ -142,7 +142,7 @@ export const runAppPullCommand: CommandRun<TargetCommandContext> = async ({hint:result.error.hint ??(result.error.code === 'SDK_SOURCE_UNSUPPORTED'- ? 'Upgrade the app to a compatible twenty-sdk version (2.40.0 or later).'+ ? 'Upgrade the app to a compatible twenty-sdk version (2.50.0 or later).': undefined),details: { ...result.error.details, diagnostics },});diff --git a/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx b/packages/twenty-docs/developers/extend/apps/logic/workflows.mdxindex bb7f811832e..3c3e3d42090 100644--- a/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx+++ b/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx@@ -101,6 +101,7 @@ Application workflows support these step types: `LOGIC_FUNCTION`, `AI_AGENT`, `HTheir inputs match the steps of the [workflow builder](/user-guide/workflows/capabilities/workflow-actions), with universal identifiers in place of names:- Record steps take `objectUniversalIdentifier` instead of an object name.- Filters and sorts point at fields with `fieldMetadataUniversalIdentifier`.+- Filter operands take `ViewFilterOperand` values, exported by `twenty-sdk/define`. Filter group operators take string values such as `'AND'` or `'OR'`.- Form fields of type `RECORD` name their object with `settings.objectUniversalIdentifier`. Fields of type `SELECT` and `MULTI_SELECT` offer the options of an existing field of the same type, named with `settings.selectedFieldUniversalIdentifier`.- To run your own code, use a `LOGIC_FUNCTION` step. The builder's Code step is not available.- Email and calendar steps run only if your app's role has the matching permission flag: `SystemPermissionFlag.SEND_EMAIL_TOOL` for `SEND_EMAIL` and `DRAFT_EMAIL`, `SystemPermissionFlag.CREATE_CALENDAR_EVENT_TOOL` for `CREATE_CALENDAR_EVENT`. The workspace grants it by installing the app, and the step can then use any connected account in the workspace, like a workflow built in the app.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.mdxindex bcb8f4c1b8a..9ee46cd907a 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@@ -130,6 +130,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;- 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.Each entity goes to the file that already defines it, so a second pull rewrites only what changed on the server. A file is also rewritten when it uses a different define function than pull would write, for example a role that became or stopped being the default role. New entities are placed beside existing files of their kind, and a generated name that would land on an unrelated file is qualified rather than overwriting it.@@ -141,6 +142,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.- **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/constants/workflow-changed-in-builder-reason.constant.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/constants/workflow-changed-in-builder-reason.constant.tsnew file mode 100644index 00000000000..87844dc79e8--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/constants/workflow-changed-in-builder-reason.constant.ts@@ -0,0 +1,2 @@+export const WORKFLOW_CHANGED_IN_BUILDER_REASON =+ 'workflow changed in the workflow builder';diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-workflow-to-workflow-manifest.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-workflow-to-workflow-manifest.util.spec.tsnew file mode 100644index 00000000000..77f11f46923--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-workflow-to-workflow-manifest.util.spec.ts@@ -0,0 +1,662 @@+import {+ type WorkflowManifest,+ type WorkflowStepManifest,+ type WorkflowTriggerManifest,+} from 'twenty-shared/application';+import {+ FieldMetadataType,+ RecordFilterGroupLogicalOperator,+ RelationType,+ StepLogicalOperator,+ ViewFilterOperand,+} from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';+import { WorkflowActionType } from 'twenty-shared/workflow';++import { fromFlatWorkflowToWorkflowManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-flat-workflow-to-workflow-manifest.util';+import { fromWorkflowManifestToUniversalFlatWorkflowOrThrow } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util';+import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';+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 APPLICATION_ID = '10000000-0000-4000-8000-000000000000';+const WORKFLOW_ID = '20000000-0000-4000-8000-000000000000';+const TRIGGER_ID = '30000000-0000-4000-8000-000000000000';+const STEP_ID = '40000000-0000-4000-8000-000000000000';+const SECOND_STEP_ID = '41000000-0000-4000-8000-000000000000';+const THIRD_STEP_ID = '42000000-0000-4000-8000-000000000000';+const OBJECT_ID = '50000000-0000-4000-8000-000000000000';+const STATUS_FIELD_ID = '60000000-0000-4000-8000-000000000000';+const COMPANY_FIELD_ID = '61000000-0000-4000-8000-000000000000';+const PRIORITY_FIELD_ID = '62000000-0000-4000-8000-000000000000';+const FUNCTION_ID = '70000000-0000-4000-8000-000000000000';+const AGENT_ID = '80000000-0000-4000-8000-000000000000';+const RECORD_FILTER_ID = '90000000-0000-4000-8000-000000000000';++const references: WorkflowManifestReferences = {+ logicFunctionIdByUniversalIdentifier: new Map([+ [FUNCTION_ID, 'logic-function-id'],+ ]),+ agentIdByUniversalIdentifier: new Map([[AGENT_ID, 'agent-id']]),+ objectByUniversalIdentifier: new Map([+ [OBJECT_ID, { nameSingular: 'ticket' }],+ ]),+ fieldByUniversalIdentifier: new Map([+ [+ STATUS_FIELD_ID,+ {+ id: 'status-field-id',+ name: 'status',+ objectUniversalIdentifier: OBJECT_ID,+ type: FieldMetadataType.TEXT,+ settings: null,+ relationTargetObjectMetadataUniversalIdentifier: null,+ },+ ],+ [+ COMPANY_FIELD_ID,+ {+ id: 'company-field-id',+ name: 'company',+ objectUniversalIdentifier: OBJECT_ID,+ type: FieldMetadataType.RELATION,+ settings: null,+ universalSettings: { relationType: RelationType.MANY_TO_ONE },+ relationTargetObjectMetadataUniversalIdentifier: OBJECT_ID,+ },+ ],+ [+ PRIORITY_FIELD_ID,+ {+ id: 'priority-field-id',+ name: 'priority',+ objectUniversalIdentifier: OBJECT_ID,+ type: FieldMetadataType.SELECT,+ settings: null,+ relationTargetObjectMetadataUniversalIdentifier: null,+ },+ ],+ ]),+};++const MANUAL_TRIGGER: WorkflowTriggerManifest = {+ universalIdentifier: TRIGGER_ID,+ type: 'MANUAL',+ nextStepIds: [STEP_ID],+};++const STEP_FILTERS = {+ stepFilterGroups: [{ id: 'group', logicalOperator: StepLogicalOperator.AND }],+ stepFilters: [+ {+ id: 'filter',+ type: 'TEXT',+ stepOutputKey: '{{trigger.properties.after.status}}',+ operand: ViewFilterOperand.IS,+ value: 'open',+ stepFilterGroupId: 'group',+ fieldMetadataUniversalIdentifier: STATUS_FIELD_ID,+ },+ ],+};++const RECORD = { objectUniversalIdentifier: OBJECT_ID };++const STEP_INPUTS = {+ LOGIC_FUNCTION: { greeting: 'Hello', nested: { count: 2 } },+ CREATE_RECORD: { ...RECORD, objectRecord: { name: 'Ticket' } },+ UPDATE_RECORD: {+ ...RECORD,+ objectRecord: { name: 'Ticket' },+ objectRecordId: '{{trigger.recordId}}',+ fieldsToUpdate: ['name'],+ },+ UPSERT_RECORD: { ...RECORD, objectRecord: { name: 'Ticket' } },+ DELETE_RECORD: { ...RECORD, objectRecordId: '{{trigger.recordId}}' },+ FIND_RECORDS: {+ ...RECORD,+ limit: 10,+ filter: {+ recordFilterGroups: [+ { id: 'root', logicalOperator: RecordFilterGroupLogicalOperator.AND },+ ],+ recordFilters: [+ {+ id: RECORD_FILTER_ID,+ fieldMetadataUniversalIdentifier: STATUS_FIELD_ID,+ operand: ViewFilterOperand.IS,+ value: 'open',+ recordFilterGroupId: 'root',+ },+ ],+ },+ orderBy: {+ recordSorts: [+ {+ fieldMetadataUniversalIdentifier: STATUS_FIELD_ID,+ direction: 'DESC',+ },+ ],+ },+ },+ PICK_RECORD: {+ ...RECORD,+ recordIds: ['{{trigger.recordId}}'],+ strategy: 'LOAD_BALANCED',+ loadBalance: {+ objectUniversalIdentifier: OBJECT_ID,+ fieldUniversalIdentifier: STATUS_FIELD_ID,+ },+ },+ FORM: [+ { id: 'name', name: 'name', label: 'Name', type: 'TEXT' },+ {+ id: 'ticket',+ name: 'ticket',+ label: 'Ticket',+ type: 'RECORD',+ settings: { objectUniversalIdentifier: OBJECT_ID },+ },+ {+ id: 'priority',+ name: 'priority',+ label: 'Priority',+ type: 'SELECT',+ settings: { selectedFieldUniversalIdentifier: PRIORITY_FIELD_ID },+ },+ ],+ HTTP_REQUEST: {+ method: 'POST',+ url: 'https://example.com',+ headers: { 'x-b': '2', 'x-a': '1' },+ body: { name: '{{trigger.name}}' },+ },+ AI_AGENT: {+ agentUniversalIdentifier: AGENT_ID,+ prompt: 'Summarize {{trigger.text}}',+ },+ CLASSIFY: { state: '{{trigger.text}}', questions: [] },+ FILTER: STEP_FILTERS,+ DELAY: { delayType: 'DURATION', duration: { seconds: 1 } },+ WAIT_FOR_EVENT: {+ eventName: 'ticket.updated',+ recordId: '{{trigger.recordId}}',+ timeout: { days: 1 },+ },+ EMPTY: {},+};++const buildStep = ({+ type,+ overrides = {},+}: {+ type: keyof typeof STEP_INPUTS;+ overrides?: Partial<WorkflowStepManifest>;+}): WorkflowStepManifest =>+ ({+ universalIdentifier: STEP_ID,+ name: `${type} step`,+ type,+ nextStepIds: [],+ input: STEP_INPUTS[type],+ ...(type === 'LOGIC_FUNCTION'+ ? { logicFunctionUniversalIdentifier: FUNCTION_ID }+ : {}),+ ...overrides,+ }) as WorkflowStepManifest;++const buildWorkflow = ({+ trigger = MANUAL_TRIGGER,+ steps = [buildStep({ type: 'EMPTY' })],+}: {+ trigger?: WorkflowTriggerManifest;+ steps?: WorkflowStepManifest[];+}): WorkflowManifest => ({+ universalIdentifier: WORKFLOW_ID,+ name: 'Triage tickets',+ version: { trigger, steps },+});++const syncWorkflow = (manifest: WorkflowManifest) => {+ const { flatUniversalWorkflowVersion, ...workflow } =+ fromWorkflowManifestToUniversalFlatWorkflowOrThrow({+ manifest,+ applicationUniversalIdentifier: APPLICATION_ID,+ now: '2026-10-26T00:00:00.000Z',+ ...references,+ });++ const flatWorkflow: FlatWorkflow = {+ ...workflow,+ workspaceId: 'workspace-id',+ applicationId: 'application-id',+ };+ // Stored versions come back from jsonb, which drops undefined values and reorders keys.+ const flatWorkflowVersion: FlatWorkflowVersion = JSON.parse(+ JSON.stringify({+ ...flatUniversalWorkflowVersion,+ workspaceId: 'workspace-id',+ applicationId: 'application-id',+ }),+ );++ return { flatWorkflow, flatWorkflowVersion };+};++const reverseKeysDeeply = <TValue>(value: TValue): TValue => {+ if (Array.isArray(value)) {+ return value.map(reverseKeysDeeply) as TValue;+ }++ if (!isDefined(value) || typeof value !== 'object') {+ return value;+ }++ return Object.fromEntries(+ Object.entries(value)+ .reverse()+ .map(([key, entry]) => [key, reverseKeysDeeply(entry)]),+ ) as TValue;+};++const exportWorkflow = ({+ flatWorkflow,+ flatWorkflowVersion,+ exportReferences = references,+}: ReturnType<typeof syncWorkflow> & {+ exportReferences?: WorkflowManifestReferences;+}) =>+ fromFlatWorkflowToWorkflowManifest({+ flatWorkflow,+ flatWorkflowVersion,+ references: exportReferences,+ });++const expectRoundTrip = (manifest: WorkflowManifest) => {+ const synced = syncWorkflow(manifest);++ expect(exportWorkflow(synced)).toEqual({ manifest });+};++const AFTER_STEP: WorkflowStepManifest = {+ universalIdentifier: SECOND_STEP_ID,+ name: 'After',+ type: 'EMPTY',+ nextStepIds: [],+ input: {},+};++const BRANCHING_STEPS: Record<'IF_ELSE' | 'ITERATOR', WorkflowStepManifest[]> =+ {+ IF_ELSE: [+ {+ universalIdentifier: STEP_ID,+ name: 'Choose',+ type: 'IF_ELSE',+ nextStepIds: [],+ input: {+ ...STEP_FILTERS,+ branches: [+ {+ id: 'open',+ nextStepIds: [SECOND_STEP_ID],+ filterGroupId: 'group',+ },+ { id: 'otherwise', nextStepIds: [THIRD_STEP_ID] },+ ],+ },+ },+ AFTER_STEP,+ {+ universalIdentifier: THIRD_STEP_ID,+ name: 'Otherwise',+ type: 'EMPTY',+ nextStepIds: [],+ input: {},+ },+ ],+ ITERATOR: [+ {+ universalIdentifier: STEP_ID,+ name: 'Repeat',+ type: 'ITERATOR',+ nextStepIds: [SECOND_STEP_ID],+ input: { items: ['one', 'two'], initialLoopStepIds: [THIRD_STEP_ID] },+ },+ AFTER_STEP,+ {+ universalIdentifier: THIRD_STEP_ID,+ name: 'Inside',+ type: 'EMPTY',+ nextStepIds: [STEP_ID],+ input: {},+ },+ ],+ };++describe('fromFlatWorkflowToWorkflowManifest', () => {+ describe('round trip through sync', () => {+ it.each(Object.keys(STEP_INPUTS) as (keyof typeof STEP_INPUTS)[])(+ 'exports a %s step as it was declared',+ (type) => {+ expectRoundTrip(buildWorkflow({ steps: [buildStep({ type })] }));+ },+ );++ it.each(['IF_ELSE', 'ITERATOR'] as const)('exports %s branches', (type) => {+ expectRoundTrip(buildWorkflow({ steps: BRANCHING_STEPS[type] }));+ });++ it('exports a position, outputs and error handling that differ from the defaults', () => {+ expectRoundTrip(+ buildWorkflow({+ steps: [+ buildStep({+ type: 'HTTP_REQUEST',+ overrides: {+ position: { x: 40, y: 90 },+ outputSchema: { response: { isLeaf: true, type: 'string' } },+ expectedOutputSchema: { ok: true },+ errorHandlingOptions: {+ retryOnFailure: { value: 2 },+ continueOnFailure: { value: true },+ },+ },+ }),+ ],+ }),+ );+ });++ it('omits values the sync derives', () => {+ const result = exportWorkflow(+ syncWorkflow(+ buildWorkflow({+ steps: [+ buildStep({+ type: 'HTTP_REQUEST',+ overrides: {+ position: { x: 0, y: 180 },+ expectedOutputSchema: { ok: true },+ errorHandlingOptions: {+ retryOnFailure: { value: 0 },+ continueOnFailure: { value: false },+ },+ },+ }),+ ],+ }),+ ),+ );++ expect(result).toEqual({+ manifest: buildWorkflow({+ steps: [+ buildStep({+ type: 'HTTP_REQUEST',+ overrides: { expectedOutputSchema: { ok: true } },+ }),+ ],+ }),+ });+ });++ it.each<WorkflowTriggerManifest>([+ {+ ...MANUAL_TRIGGER,+ settings: {+ availability: {+ type: 'SINGLE_RECORD',+ objectUniversalIdentifier: OBJECT_ID,+ },+ icon: 'IconBolt',+ isPinned: true,+ },+ },+ { ...MANUAL_TRIGGER, settings: { availability: { type: 'GLOBAL' } } },+ {+ universalIdentifier: TRIGGER_ID,+ type: 'CRON',+ nextStepIds: [STEP_ID],+ settings: { type: 'HOURS', schedule: { hour: 2, minute: 30 } },+ },+ {+ universalIdentifier: TRIGGER_ID,+ type: 'CRON',+ nextStepIds: [STEP_ID],+ settings: { type: 'CUSTOM', pattern: '0 9 * * 1' },+ },+ {+ universalIdentifier: TRIGGER_ID,+ type: 'WEBHOOK',+ nextStepIds: [STEP_ID],+ settings: { httpMethod: 'GET' },+ },+ {+ universalIdentifier: TRIGGER_ID,+ type: 'WEBHOOK',+ nextStepIds: [STEP_ID],+ settings: {+ httpMethod: 'POST',+ expectedBody: { email: '[email protected]' },+ },+ },+ {+ universalIdentifier: TRIGGER_ID,+ type: 'DATABASE_EVENT',+ nextStepIds: [STEP_ID],+ settings: { objectUniversalIdentifier: OBJECT_ID, action: 'created' },+ },+ {+ universalIdentifier: TRIGGER_ID,+ type: 'DATABASE_EVENT',+ nextStepIds: [STEP_ID],+ settings: {+ objectUniversalIdentifier: OBJECT_ID,+ action: 'updated',+ fieldUniversalIdentifiers: [STATUS_FIELD_ID, COMPANY_FIELD_ID],+ filter: STEP_FILTERS,+ },+ },+ ])('exports a $type trigger as it was declared', (trigger) => {+ expectRoundTrip(buildWorkflow({ trigger }));+ });++ it('emits the same source whatever the stored key order', () => {+ const synced = syncWorkflow(+ buildWorkflow({+ trigger: {+ universalIdentifier: TRIGGER_ID,+ type: 'DATABASE_EVENT',+ nextStepIds: [STEP_ID],+ settings: {+ objectUniversalIdentifier: OBJECT_ID,+ action: 'updated',+ filter: STEP_FILTERS,+ },+ },+ steps: [buildStep({ type: 'FIND_RECORDS' })],+ }),+ );+ const reordered = {+ ...synced,+ flatWorkflowVersion: reverseKeysDeeply(synced.flatWorkflowVersion),+ };++ expect(JSON.stringify(exportWorkflow(reordered))).toBe(+ JSON.stringify(exportWorkflow(synced)),+ );+ });+ });++ describe('unsupported workflows', () => {+ it.each([+ WorkflowActionType.CODE,+ WorkflowActionType.SEND_EMAIL,+ WorkflowActionType.DRAFT_EMAIL,+ WorkflowActionType.SEND_CHAT_MESSAGE,+ WorkflowActionType.CREATE_CALENDAR_EVENT,+ ])('reports a %s step', (type) => {+ const synced = syncWorkflow(buildWorkflow({}));+ const [step] = synced.flatWorkflowVersion.steps ?? [];++ Object.assign(step, { type });++ expect(exportWorkflow(synced)).toEqual({+ reason: `${type} steps are not supported in application workflows`,+ });+ });++ it('reports a record filter on a field of a related record', () => {+ const synced = syncWorkflow(+ buildWorkflow({ steps: [buildStep({ type: 'FIND_RECORDS' })] }),+ );+ const [step] = synced.flatWorkflowVersion.steps ?? [];++ if (step?.type !== WorkflowActionType.FIND_RECORDS) {+ throw new Error('Expected a find records step');+ }++ Object.assign(step.settings.input.filter?.recordFilters?.[0] ?? {}, {+ relationTargetFieldMetadataId: 'status-field-id',+ });++ expect(exportWorkflow(synced)).toEqual({+ reason: 'workflow filtering on a field of a related record',+ });+ });++ it('reports a webhook with authentication', () => {+ const synced = syncWorkflow(+ buildWorkflow({+ trigger: {+ universalIdentifier: TRIGGER_ID,+ type: 'WEBHOOK',+ nextStepIds: [STEP_ID],+ settings: { httpMethod: 'GET' },+ },+ }),+ );++ Object.assign(synced.flatWorkflowVersion.triggers?.[0].settings ?? {}, {+ authentication: 'API_KEY',+ });++ expect(exportWorkflow(synced)).toEqual({+ reason: 'webhook trigger with authentication',+ });+ });++ it('reports a manual trigger shown in specific locations', () => {+ const synced = syncWorkflow(+ buildWorkflow({+ trigger: {+ ...MANUAL_TRIGGER,+ settings: { availability: { type: 'GLOBAL' } },+ },+ }),+ );++ Object.assign(synced.flatWorkflowVersion.triggers?.[0].settings ?? {}, {+ availability: { type: 'GLOBAL', locations: ['tasks'] },+ });++ expect(exportWorkflow(synced)).toEqual({+ reason: 'manual trigger available in specific locations',+ });+ });++ it.each([+ {+ description: 'an object that is not exported',+ step: buildStep({ type: 'CREATE_RECORD' }),+ exportReferences: {+ ...references,+ objectByUniversalIdentifier: new Map(),+ },+ reason: 'workflow referencing an object that is not exported',+ },+ {+ description: 'a field that is not exported',+ step: buildStep({ type: 'FILTER' }),+ exportReferences: {+ ...references,+ fieldByUniversalIdentifier: new Map(),+ },+ reason: 'workflow referencing a field that is not exported',+ },+ {+ description:+ 'a logic function that is not a workflow action of the application',+ step: buildStep({ type: 'LOGIC_FUNCTION' }),+ exportReferences: {+ ...references,+ logicFunctionIdByUniversalIdentifier: new Map(),+ },+ reason:+ 'workflow step on a logic function that is not a workflow action of this application',+ },+ {+ description: 'an agent of another application',+ step: buildStep({ type: 'AI_AGENT' }),+ exportReferences: {+ ...references,+ agentIdByUniversalIdentifier: new Map(),+ },+ reason: 'workflow step on an agent of another application',+ },+ ])(+ 'reports a step on $description',+ ({ step, exportReferences, reason }) => {+ expect(+ exportWorkflow({+ ...syncWorkflow(buildWorkflow({ steps: [step] })),+ exportReferences,+ }),+ ).toEqual({ reason });+ },+ );++ it('reports a watched field that is not exported', () => {+ const synced = syncWorkflow(+ buildWorkflow({+ trigger: {+ universalIdentifier: TRIGGER_ID,+ type: 'DATABASE_EVENT',+ nextStepIds: [STEP_ID],+ settings: {+ objectUniversalIdentifier: OBJECT_ID,+ action: 'updated',+ fieldUniversalIdentifiers: [COMPANY_FIELD_ID],+ },+ },+ }),+ );++ expect(+ exportWorkflow({+ ...synced,+ exportReferences: {+ ...references,+ fieldByUniversalIdentifier: new Map(),+ },+ }),+ ).toEqual({ reason: 'workflow watching a field that is not exported' });+ });++ it('reports a version the sync would not reproduce', () => {+ const synced = syncWorkflow(buildWorkflow({}));+ const trigger = synced.flatWorkflowVersion.triggers?.[0];++ if (!isDefined(trigger)) {+ throw new Error('Expected the synced version to have a trigger');+ }++ Object.assign(trigger, { name: 'Renamed in the builder' });++ expect(exportWorkflow(synced)).toEqual({+ reason: 'workflow changed in the workflow builder',+ });+ });+ });+});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.tsnew file mode 100644index 00000000000..5c8d16bdf28--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-flat-workflow-to-workflow-manifest.util.ts@@ -0,0 +1,128 @@+import { isNonEmptyString } from '@sniptt/guards';+import isEqual from 'lodash.isequal';+import {+ type WorkflowManifest,+ type WorkflowStepManifest,+} from 'twenty-shared/application';+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';++import { WORKFLOW_CHANGED_IN_BUILDER_REASON } from 'src/engine/core-modules/application/application-manifest/constants/workflow-changed-in-builder-reason.constant';+import { fromWorkflowActionToWorkflowStepManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-action-to-workflow-step-manifest.util';+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 { 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,+ flatWorkflowVersion,+ references,+}: {+ manifest: WorkflowManifest;+ flatWorkflow: Pick<FlatWorkflow, 'applicationUniversalIdentifier'>;+ flatWorkflowVersion: Pick<+ FlatWorkflowVersion,+ 'updatedAt' | 'triggers' | 'steps'+ >;+ references: WorkflowManifestReferences;+}): boolean => {+ const reproducedVersion = fromWorkflowManifestToUniversalFlatWorkflowOrThrow({+ manifest,+ applicationUniversalIdentifier: flatWorkflow.applicationUniversalIdentifier,+ now: flatWorkflowVersion.updatedAt,+ ...references,+ }).flatUniversalWorkflowVersion;++ return isEqual(+ toJsonValue({+ triggers: reproducedVersion?.triggers,+ steps: reproducedVersion?.steps,+ }),+ toJsonValue({+ triggers: flatWorkflowVersion.triggers,+ steps: flatWorkflowVersion.steps,+ }),+ );+};++export const fromFlatWorkflowToWorkflowManifest = ({+ flatWorkflow,+ flatWorkflowVersion,+ references,+}: {+ flatWorkflow: FlatWorkflow;+ flatWorkflowVersion: FlatWorkflowVersion;+ references: WorkflowManifestReferences;+}): { manifest: WorkflowManifest } | { reason: string } => {+ const { triggers, steps } = flatWorkflowVersion;+ const [trigger] = triggers ?? [];++ if (!isNonEmptyString(flatWorkflow.name)) {+ return { reason: 'workflow without a name' };+ }++ if (triggers?.length !== 1 || !isDefined(trigger)) {+ return { reason: 'workflow without exactly one trigger' };+ }++ if (!isNonEmptyArray(steps)) {+ return { reason: 'workflow without steps' };+ }++ const triggerConversion = fromWorkflowTriggerToWorkflowTriggerManifest({+ trigger,+ references,+ });++ if ('reason' in triggerConversion) {+ return triggerConversion;+ }++ const stepManifests: WorkflowStepManifest[] = [];++ for (const [index, action] of steps.entries()) {+ const stepConversion = fromWorkflowActionToWorkflowStepManifest({+ action,+ index,+ references,+ });++ if ('reason' in stepConversion) {+ return stepConversion;+ }++ stepManifests.push(stepConversion.manifest);+ }++ const manifest: WorkflowManifest = {+ universalIdentifier: flatWorkflow.universalIdentifier,+ name: flatWorkflow.name,+ version: { trigger: triggerConversion.manifest, steps: stepManifests },+ };++ try {+ if (+ !isReproducedBySyncOrThrow({+ manifest,+ flatWorkflow,+ flatWorkflowVersion,+ references,+ })+ ) {+ return { reason: WORKFLOW_CHANGED_IN_BUILDER_REASON };+ }+ } catch (error) {+ return {+ reason: `workflow that is not a valid application workflow: ${+ error instanceof Error ? error.message : String(error)+ }`,+ };+ }++ return { manifest };+};diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-action-to-workflow-step-manifest.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-action-to-workflow-step-manifest.util.tsnew file mode 100644index 00000000000..f85833f5030--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-action-to-workflow-step-manifest.util.ts@@ -0,0 +1,314 @@+import isEqual from 'lodash.isequal';+import { type WorkflowStepManifest } from 'twenty-shared/application';+import { isDefined, isPlainObject, sortKeysDeeply } from 'twenty-shared/utils';+import { WorkflowActionType } from 'twenty-shared/workflow';++import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';+import { buildWorkflowManifestInverseReferenceResolvers } from 'src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-inverse-reference-resolvers.util';+import { computeWorkflowManifestOutputSchema } from 'src/engine/core-modules/application/application-manifest/utils/compute-workflow-manifest-output-schema.util';+import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';++type WorkflowManifestInverseReferenceResolvers = ReturnType<+ typeof buildWorkflowManifestInverseReferenceResolvers+>;++const DEFAULT_ERROR_HANDLING_OPTIONS = {+ retryOnFailure: { value: 0 },+ continueOnFailure: { value: false },+};++const toRecord = (value: unknown): Record<string, unknown> =>+ isPlainObject(value) ? value : {};++const toArray = (value: unknown): unknown[] =>+ Array.isArray(value) ? value : [];++const fromFindRecordsOrderBy = ({+ orderBy,+ resolvers,+}: {+ orderBy: Record<string, unknown>;+ resolvers: WorkflowManifestInverseReferenceResolvers;+}) => {+ const { gqlOperationOrderBy: _gqlOperationOrderBy, ...rest } = orderBy;++ return isDefined(rest.recordSorts)+ ? {+ ...rest,+ recordSorts: toArray(rest.recordSorts).map(resolvers.fieldReference),+ }+ : rest;+};++const fromFindRecordsFilter = ({+ filter,+ resolvers,+}: {+ filter: Record<string, unknown>;+ resolvers: WorkflowManifestInverseReferenceResolvers;+}) => {+ if (!isDefined(filter.recordFilters)) {+ return filter;+ }++ return {+ ...filter,+ recordFilters: toArray(filter.recordFilters).map((recordFilter) => {+ const { relationTargetFieldMetadataId, ...reference } =+ toRecord(recordFilter);++ if (isDefined(relationTargetFieldMetadataId)) {+ resolvers.markUnsupported(+ 'workflow filtering on a field of a related record',+ );+ }++ return resolvers.fieldReference(reference);+ }),+ };+};++const fromFindRecordsInput = ({+ input,+ resolvers,+}: {+ input: Record<string, unknown>;+ resolvers: WorkflowManifestInverseReferenceResolvers;+}) => {+ const { objectName, filter, orderBy, ...rest } = input;++ return {+ ...rest,+ objectUniversalIdentifier: resolvers.objectUniversalIdentifier(objectName),+ ...(isPlainObject(filter)+ ? { filter: fromFindRecordsFilter({ filter, resolvers }) }+ : {}),+ ...(isPlainObject(orderBy)+ ? { orderBy: fromFindRecordsOrderBy({ orderBy, resolvers }) }+ : {}),+ };+};++const fromPickRecordInput = ({+ input,+ resolvers,+}: {+ input: Record<string, unknown>;+ resolvers: WorkflowManifestInverseReferenceResolvers;+}) => {+ const { objectName, loadBalance, ...rest } = input;++ if (!isPlainObject(loadBalance)) {+ return {+ ...rest,+ objectUniversalIdentifier:+ resolvers.objectUniversalIdentifier(objectName),+ };+ }++ const loadBalanceObjectUniversalIdentifier =+ resolvers.objectUniversalIdentifier(loadBalance.objectNameSingular);++ return {+ ...rest,+ objectUniversalIdentifier: resolvers.objectUniversalIdentifier(objectName),+ loadBalance: {+ objectUniversalIdentifier: loadBalanceObjectUniversalIdentifier,+ fieldUniversalIdentifier: resolvers.fieldUniversalIdentifierByName({+ objectUniversalIdentifier: loadBalanceObjectUniversalIdentifier,+ fieldName: loadBalance.fieldName,+ }),+ },+ };+};++const fromFormInput = ({+ input,+ resolvers,+}: {+ input: unknown;+ resolvers: WorkflowManifestInverseReferenceResolvers;+}) =>+ toArray(input).map((formField) => {+ const field = toRecord(formField);++ if (field.type === 'SELECT' || field.type === 'MULTI_SELECT') {+ const { selectedFieldId, selectType, ...settings } = toRecord(+ field.settings,+ );++ return {+ ...field,+ settings: {+ // EXISTING_FIELD is what sync writes when the manifest omits it+ ...(isDefined(selectType) && selectType !== 'EXISTING_FIELD'+ ? { selectType }+ : {}),+ ...settings,+ selectedFieldUniversalIdentifier:+ resolvers.fieldUniversalIdentifier(selectedFieldId),+ },+ };+ }++ if (field.type !== 'RECORD') {+ return field;+ }++ const { objectName, ...settings } = toRecord(field.settings);++ return {+ ...field,+ settings: {+ ...settings,+ objectUniversalIdentifier:+ resolvers.objectUniversalIdentifier(objectName),+ },+ };+ });++const fromActionInput = ({+ action,+ resolvers,+}: {+ action: WorkflowAction;+ resolvers: WorkflowManifestInverseReferenceResolvers;+}): unknown => {+ const input: unknown = action.settings.input;++ switch (action.type) {+ case WorkflowActionType.LOGIC_FUNCTION:+ return toRecord(input).logicFunctionInput;+ case WorkflowActionType.AI_AGENT: {+ const { agentId, ...rest } = toRecord(input);++ return {+ ...rest,+ agentUniversalIdentifier: resolvers.agentUniversalIdentifier(agentId),+ };+ }+ case WorkflowActionType.CREATE_RECORD:+ case WorkflowActionType.UPDATE_RECORD:+ case WorkflowActionType.UPSERT_RECORD:+ case WorkflowActionType.DELETE_RECORD: {+ const { objectName, ...rest } = toRecord(input);++ return {+ ...rest,+ objectUniversalIdentifier:+ resolvers.objectUniversalIdentifier(objectName),+ };+ }+ case WorkflowActionType.FIND_RECORDS:+ return fromFindRecordsInput({ input: toRecord(input), resolvers });+ case WorkflowActionType.PICK_RECORD:+ return fromPickRecordInput({ input: toRecord(input), resolvers });+ case WorkflowActionType.FORM:+ return fromFormInput({ input, resolvers });+ case WorkflowActionType.FILTER:+ case WorkflowActionType.IF_ELSE: {+ const record = toRecord(input);++ return {+ ...record,+ stepFilters: toArray(record.stepFilters).map(resolvers.fieldReference),+ };+ }+ case WorkflowActionType.HTTP_REQUEST:+ case WorkflowActionType.CLASSIFY:+ case WorkflowActionType.ITERATOR:+ case WorkflowActionType.DELAY:+ case WorkflowActionType.WAIT_FOR_EVENT:+ case WorkflowActionType.EMPTY:+ return input;+ default:+ return resolvers.markUnsupported(+ `${action.type} steps are not supported in application workflows`,+ );+ }+};++export const fromWorkflowActionToWorkflowStepManifest = ({+ action,+ index,+ references,+}: {+ action: WorkflowAction;+ index: number;+ references: WorkflowManifestReferences;+}): { manifest: WorkflowStepManifest } | { reason: string } => {+ const resolvers = buildWorkflowManifestInverseReferenceResolvers(references);+ const input = sortKeysDeeply(fromActionInput({ action, resolvers }));+ const logicFunctionUniversalIdentifier =+ action.type === WorkflowActionType.LOGIC_FUNCTION+ ? resolvers.logicFunctionUniversalIdentifier(+ action.settings.input.logicFunctionId,+ )+ : undefined;+ const unsupportedReason = resolvers.getUnsupportedReason();++ if (isDefined(unsupportedReason)) {+ return { reason: unsupportedReason };+ }++ const { outputSchema, errorHandlingOptions } = action.settings;+ const expectedOutputSchema =+ 'expectedOutputSchema' in action.settings+ ? action.settings.expectedOutputSchema+ : undefined;+ const stepWithoutOutputSchema = {+ universalIdentifier: action.id,+ name: action.name,+ type: action.type,+ ...(isDefined(logicFunctionUniversalIdentifier)+ ? { logicFunctionUniversalIdentifier }+ : {}),+ nextStepIds: action.nextStepIds ?? [],+ ...(isDefined(action.position) &&+ !isEqual(action.position, { x: 0, y: (index + 1) * 180 })+ ? { position: { x: action.position.x, y: action.position.y } }+ : {}),+ input,+ } as WorkflowStepManifest;+ const isDefaultOutputSchema = isEqual(+ outputSchema,+ computeWorkflowManifestOutputSchema({+ step: {+ ...stepWithoutOutputSchema,+ ...(isDefined(expectedOutputSchema)+ ? { expectedOutputSchema: toRecord(expectedOutputSchema) }+ : {}),+ },+ references,+ }),+ );++ return {+ manifest: {+ ...stepWithoutOutputSchema,+ ...(isDefaultOutputSchema+ ? {}+ : { outputSchema: sortKeysDeeply(toRecord(outputSchema)) }),+ ...(isDefined(expectedOutputSchema)+ ? {+ expectedOutputSchema: sortKeysDeeply(+ toRecord(expectedOutputSchema),+ ),+ }+ : {}),+ ...(!isDefined(errorHandlingOptions) ||+ isEqual(errorHandlingOptions, DEFAULT_ERROR_HANDLING_OPTIONS)+ ? {}+ : {+ errorHandlingOptions: {+ retryOnFailure: {+ value: errorHandlingOptions.retryOnFailure.value,+ },+ continueOnFailure: {+ value: errorHandlingOptions.continueOnFailure.value,+ },+ },+ }),+ },+ };+};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.tsindex daea853095d..97a2ae0cd73 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@@ -5,7 +5,7 @@ import { fromWorkflowStepManifestToActionOrThrow } from 'src/engine/core-modulesimport { 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 { msg } from '@lingui/core/macro';-import { isDefined } from 'twenty-shared/utils';+import { isDefined, sortKeysDeeply } from 'twenty-shared/utils';import {ApplicationException,ApplicationExceptionCode,@@ -92,7 +92,7 @@ export const fromWorkflowManifestToUniversalFlatWorkflowOrThrow = ({createdAt: existingWorkflow?.createdAt ?? now,updatedAt: now,versionDefinitionHash: createHash('sha256')- .update(JSON.stringify({ trigger, steps }))+ .update(JSON.stringify(sortKeysDeeply({ trigger, steps }))).digest('hex'),flatUniversalWorkflowVersion: {id: versionId,diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-trigger-manifest-to-trigger-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-trigger-manifest-to-trigger-or-throw.util.tsindex 01e07ed2772..dcf4417606c 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-trigger-manifest-to-trigger-or-throw.util.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-trigger-manifest-to-trigger-or-throw.util.ts@@ -1,13 +1,13 @@import { msg } from '@lingui/core/macro';import { type WorkflowTriggerManifest } from 'twenty-shared/application';import { getOutputSchemaFromValue } from 'twenty-shared/logic-function';-import { FieldMetadataType, RelationType } from 'twenty-shared/types';import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';import {type WorkflowManifestFieldReference,type WorkflowManifestReferences,} from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';+import { computeWorkflowWatchedFieldName } from 'src/engine/core-modules/application/application-manifest/utils/compute-workflow-watched-field-name.util';import { buildWorkflowManifestReferenceResolvers } from 'src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-reference-resolvers.util';import {ApplicationException,@@ -23,7 +23,6 @@ import {type WorkflowWebhookTrigger,} from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';import { computeCronPatternFromSchedule } from 'src/modules/workflow/workflow-trigger/utils/compute-cron-pattern-from-schedule';-import { computeMorphOrRelationFieldJoinColumnName } from 'src/engine/metadata-modules/field-metadata/utils/compute-morph-or-relation-field-join-column-name.util';import { computeEventName } from 'src/engine/workspace-event-emitter/utils/compute-event-name';import { assertNever } from 'src/utils/assert';@@ -126,18 +125,9 @@ const fromCronTriggerManifestOrThrow = (const toWatchedFieldNameOrThrow = (field: WorkflowManifestFieldReference,): string => {- if (- field.type !== FieldMetadataType.RELATION &&- field.type !== FieldMetadataType.MORPH_RELATION- ) {- return field.name;- }+ const watchedFieldName = computeWorkflowWatchedFieldName(field);- if (- !isDefined(field.universalSettings) ||- !('relationType' in field.universalSettings) ||- field.universalSettings.relationType !== RelationType.MANY_TO_ONE- ) {+ if (!isDefined(watchedFieldName)) {throw new ApplicationException(`Workflow trigger: ${field.name} cannot be watched, only relations to a single record change on update`,ApplicationExceptionCode.INVALID_INPUT,@@ -147,7 +137,7 @@ const toWatchedFieldNameOrThrow = ();}- return computeMorphOrRelationFieldJoinColumnName({ name: field.name });+ return watchedFieldName;};const fromDatabaseEventTriggerManifestOrThrow = ({diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-trigger-to-workflow-trigger-manifest.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-trigger-to-workflow-trigger-manifest.util.tsnew file mode 100644index 00000000000..aede6269242--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-trigger-to-workflow-trigger-manifest.util.ts@@ -0,0 +1,203 @@+import { type WorkflowTriggerManifest } from 'twenty-shared/application';+import {+ isDefined,+ isNonEmptyArray,+ sortKeysDeeply,+} from 'twenty-shared/utils';++import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';+import { buildWorkflowManifestInverseReferenceResolvers } from 'src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-inverse-reference-resolvers.util';+import { type UpdateEventTriggerSettings } from 'src/modules/workflow/workflow-trigger/automated-trigger/constants/automated-trigger-settings';+import {+ type WorkflowCronTrigger,+ type WorkflowDatabaseEventTrigger,+ type WorkflowManualTrigger,+ type WorkflowTrigger,+ WorkflowTriggerType,+ type WorkflowWebhookTrigger,+} from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';++type WorkflowManifestInverseReferenceResolvers = ReturnType<+ typeof buildWorkflowManifestInverseReferenceResolvers+>;++const fromManualTriggerAvailability = ({+ availability,+ resolvers,+}: {+ availability: NonNullable<WorkflowManualTrigger['settings']['availability']>;+ resolvers: WorkflowManifestInverseReferenceResolvers;+}) => {+ if (availability.type === 'GLOBAL') {+ return { type: availability.type };+ }++ return {+ type: availability.type,+ objectUniversalIdentifier: resolvers.objectUniversalIdentifier(+ availability.objectNameSingular,+ ),+ };+};++const fromManualTriggerSettings = ({+ settings,+ resolvers,+}: {+ settings: WorkflowManualTrigger['settings'];+ resolvers: WorkflowManifestInverseReferenceResolvers;+}) => {+ const { availability, icon, isPinned } = settings;++ if (!isDefined(availability) && !isDefined(icon) && !isDefined(isPinned)) {+ return undefined;+ }++ if (+ isDefined(availability) &&+ 'locations' in availability &&+ isDefined(availability.locations)+ ) {+ resolvers.markUnsupported('manual trigger available in specific locations');+ }++ return {+ ...(isDefined(availability)+ ? {+ availability: fromManualTriggerAvailability({+ availability,+ resolvers,+ }),+ }+ : {}),+ ...(isDefined(icon) ? { icon } : {}),+ ...(isDefined(isPinned) ? { isPinned } : {}),+ };+};++const fromCronTriggerSettings = (settings: WorkflowCronTrigger['settings']) => {+ const { outputSchema: _outputSchema, ...rest } = settings;++ return rest;+};++const fromDatabaseEventTriggerSettings = ({+ settings,+ resolvers,+}: {+ settings: WorkflowDatabaseEventTrigger['settings'] &+ Partial<UpdateEventTriggerSettings>;+ resolvers: WorkflowManifestInverseReferenceResolvers;+}) => {+ const [objectName, action, ...extraSegments] = settings.eventName.split('.');++ if (extraSegments.length > 0 || !isDefined(action)) {+ resolvers.markUnsupported('record event trigger on an unknown event');+ }++ const objectUniversalIdentifier =+ resolvers.objectUniversalIdentifier(objectName);+ const { fields, filter } = settings;++ return {+ objectUniversalIdentifier,+ action,+ ...(isNonEmptyArray(fields)+ ? {+ fieldUniversalIdentifiers: fields.map((watchedFieldName) =>+ resolvers.watchedFieldUniversalIdentifier({+ objectUniversalIdentifier,+ watchedFieldName,+ }),+ ),+ }+ : {}),+ ...(isDefined(filter)+ ? {+ filter: {+ stepFilterGroups: filter.stepFilterGroups,+ stepFilters: filter.stepFilters.map(resolvers.fieldReference),+ },+ }+ : {}),+ };+};++const fromWebhookTriggerSettings = ({+ settings,+ resolvers,+}: {+ settings: WorkflowWebhookTrigger['settings'];+ resolvers: WorkflowManifestInverseReferenceResolvers;+}) => {+ if (isDefined(settings.authentication)) {+ resolvers.markUnsupported('webhook trigger with authentication');+ }++ return settings.httpMethod === 'GET'+ ? { httpMethod: settings.httpMethod }+ : { httpMethod: settings.httpMethod, expectedBody: settings.expectedBody };+};++const fromTriggerSettings = ({+ trigger,+ resolvers,+}: {+ trigger: WorkflowTrigger;+ resolvers: WorkflowManifestInverseReferenceResolvers;+}): unknown => {+ const triggerType: string = trigger.type;++ switch (trigger.type) {+ case WorkflowTriggerType.MANUAL:+ return fromManualTriggerSettings({+ settings: trigger.settings,+ resolvers,+ });+ case WorkflowTriggerType.CRON:+ return fromCronTriggerSettings(trigger.settings);+ case WorkflowTriggerType.DATABASE_EVENT:+ return fromDatabaseEventTriggerSettings({+ settings: trigger.settings,+ resolvers,+ });+ case WorkflowTriggerType.WEBHOOK:+ return fromWebhookTriggerSettings({+ settings: trigger.settings,+ resolvers,+ });+ default:+ return resolvers.markUnsupported(+ `${triggerType} triggers are not supported in application workflows`,+ );+ }+};++export const fromWorkflowTriggerToWorkflowTriggerManifest = ({+ trigger,+ references,+}: {+ trigger: WorkflowTrigger & { universalIdentifier?: string };+ references: WorkflowManifestReferences;+}): { manifest: WorkflowTriggerManifest } | { reason: string } => {+ if (!isDefined(trigger.universalIdentifier)) {+ return { reason: 'workflow trigger without a universal identifier' };+ }++ const resolvers = buildWorkflowManifestInverseReferenceResolvers(references);+ const settings = fromTriggerSettings({ trigger, resolvers });+ const unsupportedReason = resolvers.getUnsupportedReason();++ if (isDefined(unsupportedReason)) {+ return { reason: unsupportedReason };+ }++ return {+ manifest: {+ universalIdentifier: trigger.universalIdentifier,+ type: trigger.type,+ nextStepIds: trigger.nextStepIds ?? [],+ ...(isDefined(settings) ? { settings: sortKeysDeeply(settings) } : {}),+ } as WorkflowTriggerManifest,+ };+};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.tsindex 6d60290881c..d3373c513a7 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@@ -15,12 +15,14 @@ import { reconstructNavigationMenuItemsManifest } from 'src/engine/core-modules/import { reconstructPageLayoutsManifest } from 'src/engine/core-modules/application/application-manifest/utils/reconstruct-page-layouts-manifest.util';import { reconstructRolesManifest } from 'src/engine/core-modules/application/application-manifest/utils/reconstruct-roles-manifest.util';import { reconstructViewsManifest } from 'src/engine/core-modules/application/application-manifest/utils/reconstruct-views-manifest.util';+import { reconstructWorkflowsManifest } from 'src/engine/core-modules/application/application-manifest/utils/reconstruct-workflows-manifest.util';import { ApplicationRegistrationLookupService } from 'src/engine/core-modules/application/application-registration/application-registration-lookup/application-registration-lookup.service';import { ApplicationTranslationCacheService } from 'src/engine/core-modules/application/application-translation/application-translation-cache.service';import {ApplicationException,ApplicationExceptionCode,} from 'src/engine/core-modules/application/application.exception';+import { ApplicationService } from 'src/engine/core-modules/application/application.service';import { findActiveFlatApplicationByUniversalIdentifier } from 'src/engine/core-modules/application/utils/find-active-flat-application-by-universal-identifier.util';import { getMetadataFlatEntityMapsKey } from 'src/engine/metadata-modules/flat-entity/utils/get-metadata-flat-entity-maps-key.util';import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';@@ -44,6 +46,7 @@ export class ApplicationManifestExportService {private readonly workspaceCacheService: WorkspaceCacheService,private readonly applicationTranslationCacheService: ApplicationTranslationCacheService,private readonly applicationRegistrationLookupService: ApplicationRegistrationLookupService,+ private readonly applicationService: ApplicationService,) {}async exportApplication({@@ -94,6 +97,11 @@ export class ApplicationManifestExportService {const exportedObjectUniversalIdentifiers = new Set(objects.map(({ universalIdentifier }) => universalIdentifier),);+ const resolvableFieldUniversalIdentifiers =+ getResolvableReferenceUniversalIdentifiers({+ coverage: dataModelCoverage,+ metadataName: 'fieldMetadata',+ });const {permissionFlags,roles,@@ -102,11 +110,7 @@ export class ApplicationManifestExportService {applicationAllFlatEntityMaps,allFlatEntityMaps,exportedObjectUniversalIdentifiers,- resolvableFieldUniversalIdentifiers:- getResolvableReferenceUniversalIdentifiers({- coverage: dataModelCoverage,- metadataName: 'fieldMetadata',- }),+ resolvableFieldUniversalIdentifiers,});const {views,@@ -143,6 +147,19 @@ export class ApplicationManifestExportService {metadataName: 'pageLayout',}),});+ const { workspaceCustomFlatApplication } =+ await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(+ { workspaceId },+ );+ const { workflows, coverage: workflowsCoverage } =+ reconstructWorkflowsManifest({+ applicationAllFlatEntityMaps,+ allFlatEntityMaps,+ exportedObjectUniversalIdentifiers,+ resolvableFieldUniversalIdentifiers,+ canReferenceOtherApplicationsWorkflowActions:+ flatApplication.id === workspaceCustomFlatApplication.id,+ });const translations = isDefined(flatApplication.applicationRegistrationId)? await this.applicationTranslationCacheService.getCatalogsByLocale(flatApplication.applicationRegistrationId,@@ -177,6 +194,7 @@ export class ApplicationManifestExportService {commandMenuItems: [],timelineActivityTypes: [],settingsMenuItems: [],+ workflows,...(isDefined(translations) ? { translations } : {}),};@@ -197,6 +215,7 @@ export class ApplicationManifestExportService {...viewsCoverage,...pageLayoutsCoverage,...navigationMenuItemsCoverage,+ ...workflowsCoverage,],}),files: [],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.tsindex f5e0eade2c1..68a1fb26160 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@@ -17,6 +17,7 @@ import {type ViewGroupManifest,type ViewManifest,type ViewSortManifest,+ type WorkflowManifest,} from 'twenty-shared/application';import {AggregateOperations,@@ -35,6 +36,7 @@ import {ViewVisibility,WidgetType,} from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';import { fromFieldPermissionManifestToUniversalFlatFieldPermission } from 'src/engine/core-modules/application/application-manifest/converters/from-field-permission-manifest-to-universal-flat-field-permission.util';import { fromFlatFieldMetadataToFieldManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-flat-field-metadata-to-field-manifest.util';@@ -72,6 +74,8 @@ import { fromViewFilterGroupManifestToUniversalFlatViewFilterGroup } from 'src/eimport { fromViewFilterManifestToUniversalFlatViewFilter } from 'src/engine/core-modules/application/application-manifest/converters/from-view-filter-manifest-to-universal-flat-view-filter.util';import { fromViewGroupManifestToUniversalFlatViewGroup } from 'src/engine/core-modules/application/application-manifest/converters/from-view-group-manifest-to-universal-flat-view-group.util';import { fromViewManifestToUniversalFlatView } from 'src/engine/core-modules/application/application-manifest/converters/from-view-manifest-to-universal-flat-view.util';+import { fromFlatWorkflowToWorkflowManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-flat-workflow-to-workflow-manifest.util';+import { fromWorkflowManifestToUniversalFlatWorkflowOrThrow } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util';import { fromViewSortManifestToUniversalFlatViewSort } from 'src/engine/core-modules/application/application-manifest/converters/from-view-sort-manifest-to-universal-flat-view-sort.util';import { ALL_UNIVERSAL_FLAT_ENTITY_PROPERTIES_TO_COMPARE_AND_STRINGIFY } from 'src/engine/metadata-modules/flat-entity/constant/all-universal-flat-entity-properties-to-compare-and-stringify.constant';import { getFlatFieldMetadataMock } from 'src/engine/metadata-modules/flat-field-metadata/__mocks__/get-flat-field-metadata.mock';@@ -334,6 +338,61 @@ const ROW_LEVEL_PERMISSION_KIND_GAPS = {'soft-deleted row-level permission predicates and groups are reported as excluded instead of exported',};+const WORKFLOW_MANIFEST: WorkflowManifest = {+ universalIdentifier: APP_UID,+ name: 'Workflow',+ version: {+ trigger: {+ universalIdentifier: OBJECT_UID,+ type: 'MANUAL',+ nextStepIds: [FIELD_UID],+ },+ steps: [+ {+ universalIdentifier: FIELD_UID,+ name: 'Empty',+ type: 'EMPTY',+ nextStepIds: [],+ input: {},+ },+ ],+ },+};++const exportWorkflowManifestOrThrow = (manifest: WorkflowManifest) => {+ const references = { logicFunctionIdByUniversalIdentifier: new Map() };+ const { flatUniversalWorkflowVersion, ...universalFlatWorkflow } =+ fromWorkflowManifestToUniversalFlatWorkflowOrThrow({+ manifest,+ applicationUniversalIdentifier: APP_UID,+ now: NOW,+ ...references,+ });++ if (!isDefined(flatUniversalWorkflowVersion)) {+ throw new Error('Expected the synced workflow version');+ }+ const conversion = fromFlatWorkflowToWorkflowManifest({+ flatWorkflow: {+ ...universalFlatWorkflow,+ workspaceId: 'workspace-id',+ applicationId: 'application-id',+ },+ flatWorkflowVersion: {+ ...flatUniversalWorkflowVersion,+ workspaceId: 'workspace-id',+ applicationId: 'application-id',+ },+ references,+ });++ if ('reason' in conversion) {+ throw new Error(conversion.reason);+ }++ return conversion.manifest;+};+type ExportedKind = {metadataName: keyof typeof ALL_UNIVERSAL_FLAT_ENTITY_PROPERTIES_TO_COMPARE_AND_STRINGIFY;emittedProperties: string[];@@ -737,6 +796,23 @@ const EXPORTED_KINDS: ExportedKind[] = [workspaceLocalProperties: [],knownGaps: {},},+ {+ metadataName: 'workflow',+ emittedProperties: Object.keys(+ exportWorkflowManifestOrThrow(WORKFLOW_MANIFEST),+ ),+ renamedProperties: { versionDefinitionHash: 'version' },+ workspaceLocalProperties: [],+ 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',+ lastPublishedCoreWorkflowVersionId:+ 'the sync points it at the version it derives from the definition',+ },+ },];describe('export coverage of the compared properties', () => {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.tsnew file mode 100644index 00000000000..d1594cc779b--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-workflows-manifest.util.spec.ts@@ -0,0 +1,440 @@+import { type WorkflowManifest } from 'twenty-shared/application';+import { WorkflowVisibility } from 'twenty-shared/types';+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 { addAllFlatEntitiesToFlatEntityMaps } from 'src/engine/core-modules/application/application-manifest/utils/__tests__/add-all-flat-entities-to-flat-entity-maps.test-util';+import { reconstructWorkflowsManifest } from 'src/engine/core-modules/application/application-manifest/utils/reconstruct-workflows-manifest.util';+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 { createEmptyAllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-all-flat-entity-maps.constant';+import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';+import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';+import { getFlatObjectMetadataMock } from 'src/engine/metadata-modules/flat-object-metadata/__mocks__/get-flat-object-metadata.mock';+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 { type FlatWorkflowVersion } from 'src/engine/metadata-modules/flat-workflow-version/types/flat-workflow-version.type';++const APP_ID = 'application-id';+const OTHER_APP_ID = 'other-application-id';+const WORKSPACE_ID = 'workspace-id';+const NOW = '2026-10-26T00:00:00.000Z';+const APP_UID = '11111111-1111-4111-8111-111111111111';+const TICKET_UID = '22222222-2222-4222-8222-222222222222';+const UNEXPORTED_OBJECT_UID = '33333333-3333-4333-8333-333333333333';+const COMPANY_UID = '44444444-4444-4444-8444-444444444444';+const ACTION_FUNCTION_UID = '55555555-5555-4555-8555-555555555555';+const PLAIN_FUNCTION_UID = '66666666-6666-4666-8666-666666666666';+const OTHER_APPLICATION_FUNCTION_UID = '99999999-9999-4999-8999-999999999999';+const TRIGGER_UID = '77777777-7777-4777-8777-777777777777';+const STEP_UID = '88888888-8888-4888-8888-888888888888';++const buildObject = ({+ universalIdentifier,+ applicationId,+ nameSingular,+}: {+ universalIdentifier: string;+ applicationId: string;+ nameSingular: string;+}): FlatObjectMetadata =>+ getFlatObjectMetadataMock({+ universalIdentifier,+ applicationId,+ applicationUniversalIdentifier: APP_UID,+ nameSingular,+ namePlural: `${nameSingular}s`,+ });++const ticketObject = buildObject({+ universalIdentifier: TICKET_UID,+ applicationId: APP_ID,+ nameSingular: 'ticket',+});+const unexportedObject = buildObject({+ universalIdentifier: UNEXPORTED_OBJECT_UID,+ applicationId: APP_ID,+ nameSingular: 'draft',+});+const companyObject = buildObject({+ universalIdentifier: COMPANY_UID,+ applicationId: OTHER_APP_ID,+ nameSingular: 'company',+});++const buildLogicFunction = ({+ universalIdentifier,+ isWorkflowAction,+ applicationId = APP_ID,+}: {+ universalIdentifier: string;+ isWorkflowAction: boolean;+ applicationId?: string;+}) =>+ ({+ id: `${universalIdentifier}-id`,+ universalIdentifier,+ applicationId,+ applicationUniversalIdentifier: APP_UID,+ workflowActionTriggerSettings: isWorkflowAction ? {} : null,+ }) as FlatLogicFunction;++const logicFunctions = [+ buildLogicFunction({+ universalIdentifier: ACTION_FUNCTION_UID,+ isWorkflowAction: true,+ }),+ buildLogicFunction({+ universalIdentifier: PLAIN_FUNCTION_UID,+ isWorkflowAction: false,+ }),+];+const otherApplicationActionFunction = buildLogicFunction({+ universalIdentifier: OTHER_APPLICATION_FUNCTION_UID,+ isWorkflowAction: true,+ applicationId: OTHER_APP_ID,+});++const createRecordWorkflow = ({+ universalIdentifier,+ objectUniversalIdentifier,+}: {+ universalIdentifier: string;+ objectUniversalIdentifier: string;+}): WorkflowManifest => ({+ universalIdentifier,+ name: `Workflow ${universalIdentifier.slice(0, 2)}`,+ version: {+ trigger: {+ universalIdentifier: TRIGGER_UID,+ type: 'MANUAL',+ nextStepIds: [STEP_UID],+ },+ steps: [+ {+ universalIdentifier: STEP_UID,+ name: 'Create',+ type: 'CREATE_RECORD',+ nextStepIds: [],+ input: { objectUniversalIdentifier, objectRecord: {} },+ },+ ],+ },+});++const logicFunctionWorkflow = ({+ universalIdentifier,+ logicFunctionUniversalIdentifier,+}: {+ universalIdentifier: string;+ logicFunctionUniversalIdentifier: string;+}): WorkflowManifest => ({+ universalIdentifier,+ name: `Workflow ${universalIdentifier.slice(0, 2)}`,+ version: {+ trigger: {+ universalIdentifier: TRIGGER_UID,+ type: 'MANUAL',+ nextStepIds: [STEP_UID],+ },+ steps: [+ {+ universalIdentifier: STEP_UID,+ name: 'Run',+ type: 'LOGIC_FUNCTION',+ logicFunctionUniversalIdentifier,+ nextStepIds: [],+ input: { greeting: 'Hello' },+ },+ ],+ },+});++const syncWorkflow = ({+ manifest,+ workflowOverrides = {},+ versionOverrides = {},+}: {+ manifest: WorkflowManifest;+ workflowOverrides?: Partial<FlatWorkflow>;+ versionOverrides?: Partial<FlatWorkflowVersion>;+}): {+ flatWorkflow: FlatWorkflow;+ flatWorkflowVersion: FlatWorkflowVersion;+} => {+ const { flatUniversalWorkflowVersion, ...universalFlatWorkflow } =+ fromWorkflowManifestToUniversalFlatWorkflowOrThrow({+ manifest,+ applicationUniversalIdentifier: APP_UID,+ now: NOW,+ logicFunctionIdByUniversalIdentifier: new Map(+ [...logicFunctions, otherApplicationActionFunction].map(+ ({ universalIdentifier, id }) => [universalIdentifier, id],+ ),+ ),+ objectByUniversalIdentifier: new Map(+ [ticketObject, unexportedObject, companyObject].map((object) => [+ object.universalIdentifier,+ object,+ ]),+ ),+ });++ if (!isDefined(flatUniversalWorkflowVersion)) {+ throw new Error('Expected the synced workflow version');+ }++ return {+ flatWorkflow: {+ ...universalFlatWorkflow,+ workspaceId: WORKSPACE_ID,+ applicationId: APP_ID,+ ...workflowOverrides,+ },+ flatWorkflowVersion: {+ ...flatUniversalWorkflowVersion,+ workspaceId: WORKSPACE_ID,+ applicationId: APP_ID,+ ...versionOverrides,+ },+ };+};++const buildMaps = ({+ objects = [],+ flatLogicFunctions = logicFunctions,+ synced,+}: {+ objects?: FlatObjectMetadata[];+ flatLogicFunctions?: FlatLogicFunction[];+ synced: ReturnType<typeof syncWorkflow>[];+}): AllFlatEntityMaps => {+ const maps = createEmptyAllFlatEntityMaps();++ return {+ ...maps,+ flatObjectMetadataMaps: addAllFlatEntitiesToFlatEntityMaps({+ flatEntities: objects,+ flatEntityMaps: maps.flatObjectMetadataMaps,+ }),+ flatLogicFunctionMaps: addAllFlatEntitiesToFlatEntityMaps({+ flatEntities: flatLogicFunctions,+ flatEntityMaps: maps.flatLogicFunctionMaps,+ }),+ flatWorkflowMaps: addAllFlatEntitiesToFlatEntityMaps({+ flatEntities: synced.map(({ flatWorkflow }) => flatWorkflow),+ flatEntityMaps: maps.flatWorkflowMaps,+ }),+ flatWorkflowVersionMaps: addAllFlatEntitiesToFlatEntityMaps({+ flatEntities: synced.map(+ ({ flatWorkflowVersion }) => flatWorkflowVersion,+ ),+ flatEntityMaps: maps.flatWorkflowVersionMaps,+ }),+ };+};++const reconstruct = ({+ synced,+ canReferenceOtherApplicationsWorkflowActions = false,+}: {+ synced: ReturnType<typeof syncWorkflow>[];+ canReferenceOtherApplicationsWorkflowActions?: boolean;+}) =>+ reconstructWorkflowsManifest({+ applicationAllFlatEntityMaps: buildMaps({+ objects: [ticketObject, unexportedObject],+ synced,+ }),+ allFlatEntityMaps: buildMaps({+ objects: [ticketObject, unexportedObject, companyObject],+ flatLogicFunctions: [...logicFunctions, otherApplicationActionFunction],+ synced,+ }),+ exportedObjectUniversalIdentifiers: new Set([TICKET_UID]),+ resolvableFieldUniversalIdentifiers: new Set(),+ canReferenceOtherApplicationsWorkflowActions,+ });++describe('reconstructWorkflowsManifest', () => {+ it('exports workflows on exported objects, other applications objects and workflow action functions', () => {+ const manifests = [+ createRecordWorkflow({+ universalIdentifier: 'a0000000-0000-4000-8000-000000000000',+ objectUniversalIdentifier: TICKET_UID,+ }),+ createRecordWorkflow({+ universalIdentifier: 'a1000000-0000-4000-8000-000000000000',+ objectUniversalIdentifier: COMPANY_UID,+ }),+ logicFunctionWorkflow({+ universalIdentifier: 'a2000000-0000-4000-8000-000000000000',+ logicFunctionUniversalIdentifier: ACTION_FUNCTION_UID,+ }),+ ];++ const { workflows, coverage } = reconstruct({+ synced: manifests.map((manifest) => syncWorkflow({ manifest })),+ });++ expect(workflows).toEqual(manifests);+ expect(coverage).toEqual(+ manifests.map(({ universalIdentifier }) => ({+ metadataName: 'workflow',+ universalIdentifier,+ status: ApplicationExportCoverageStatus.EXPORTED,+ })),+ );+ });++ it('reports every workflow it does not export', () => {+ const manifest = (universalIdentifier: string) =>+ createRecordWorkflow({+ universalIdentifier,+ objectUniversalIdentifier: TICKET_UID,+ });+ const synced = [+ syncWorkflow({+ manifest: manifest('b0000000-0000-4000-8000-000000000000'),+ workflowOverrides: { isSystem: true },+ }),+ syncWorkflow({+ manifest: manifest('b1000000-0000-4000-8000-000000000000'),+ workflowOverrides: { visibility: WorkflowVisibility.PRIVATE },+ }),+ syncWorkflow({+ manifest: manifest('b2000000-0000-4000-8000-000000000000'),+ workflowOverrides: { lastPublishedCoreWorkflowVersionId: 'other' },+ }),+ syncWorkflow({+ manifest: manifest('b3000000-0000-4000-8000-000000000000'),+ versionOverrides: { status: WorkflowVersionStatus.DEACTIVATED },+ }),+ syncWorkflow({+ 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',+ objectUniversalIdentifier: UNEXPORTED_OBJECT_UID,+ }),+ }),+ syncWorkflow({+ manifest: logicFunctionWorkflow({+ universalIdentifier: 'b7000000-0000-4000-8000-000000000000',+ logicFunctionUniversalIdentifier: PLAIN_FUNCTION_UID,+ }),+ }),+ ];++ expect(reconstruct({ synced })).toEqual({+ workflows: [],+ coverage: [+ {+ metadataName: 'workflow',+ universalIdentifier: 'b0000000-0000-4000-8000-000000000000',+ status: ApplicationExportCoverageStatus.EXCLUDED,+ reason: 'system workflow',+ },+ {+ metadataName: 'workflow',+ universalIdentifier: 'b1000000-0000-4000-8000-000000000000',+ status: ApplicationExportCoverageStatus.EXCLUDED,+ reason: 'private workflow',+ },+ ...[+ 'b2000000-0000-4000-8000-000000000000',+ 'b3000000-0000-4000-8000-000000000000',+ 'b4000000-0000-4000-8000-000000000000',+ ].map((universalIdentifier) => ({+ metadataName: 'workflow',+ universalIdentifier,+ 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',+ status: ApplicationExportCoverageStatus.UNSUPPORTED,+ reason: 'workflow referencing an object that is not exported',+ },+ {+ metadataName: 'workflow',+ universalIdentifier: 'b7000000-0000-4000-8000-000000000000',+ status: ApplicationExportCoverageStatus.UNSUPPORTED,+ reason:+ 'workflow step on a logic function that is not a workflow action of this application',+ },+ ],+ });+ });++ it('exports a step on another application action only from the workspace custom application', () => {+ const manifest = logicFunctionWorkflow({+ universalIdentifier: 'd0000000-0000-4000-8000-000000000000',+ logicFunctionUniversalIdentifier: OTHER_APPLICATION_FUNCTION_UID,+ });+ const synced = [syncWorkflow({ manifest })];++ expect(reconstruct({ synced }).coverage).toEqual([+ {+ metadataName: 'workflow',+ universalIdentifier: 'd0000000-0000-4000-8000-000000000000',+ status: ApplicationExportCoverageStatus.UNSUPPORTED,+ reason:+ 'workflow step on a logic function that is not a workflow action of this application',+ },+ ]);+ expect(+ reconstruct({+ synced,+ canReferenceOtherApplicationsWorkflowActions: true,+ }).workflows,+ ).toEqual([manifest]);+ });++ it('reports a workflow whose synced version is missing', () => {+ const { flatWorkflow } = syncWorkflow({+ manifest: createRecordWorkflow({+ universalIdentifier: 'c0000000-0000-4000-8000-000000000000',+ objectUniversalIdentifier: TICKET_UID,+ }),+ });+ const maps = buildMaps({ objects: [ticketObject], synced: [] });+ const mapsWithWorkflow = {+ ...maps,+ flatWorkflowMaps: addAllFlatEntitiesToFlatEntityMaps({+ flatEntities: [flatWorkflow],+ flatEntityMaps: maps.flatWorkflowMaps,+ }),+ };++ expect(+ reconstructWorkflowsManifest({+ applicationAllFlatEntityMaps: mapsWithWorkflow,+ allFlatEntityMaps: mapsWithWorkflow,+ exportedObjectUniversalIdentifiers: new Set([TICKET_UID]),+ resolvableFieldUniversalIdentifiers: new Set(),+ canReferenceOtherApplicationsWorkflowActions: false,+ }).coverage,+ ).toEqual([+ {+ metadataName: 'workflow',+ universalIdentifier: 'c0000000-0000-4000-8000-000000000000',+ status: ApplicationExportCoverageStatus.UNSUPPORTED,+ reason: 'workflow changed in the workflow builder',+ },+ ]);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-export-references.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-export-references.util.tsnew file mode 100644index 00000000000..3d4515e93c0--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-export-references.util.ts@@ -0,0 +1,149 @@+import { inputSchemaToOutputSchema } from 'twenty-shared/logic-function';+import { isDefined } from 'twenty-shared/utils';+import { type BaseOutputSchemaV2 } from 'twenty-shared/workflow';++import {+ type WorkflowManifestFieldReference,+ type WorkflowManifestObjectReference,+ type WorkflowManifestReferences,+} from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';+import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';+import { computeAiAgentOutputSchema } from 'src/modules/workflow/workflow-builder/workflow-schema/utils/compute-ai-agent-output-schema.util';++// Mirrors prepareWorkflowManifestReferences: own metadata resolves only if exported, foreign always.+export const buildWorkflowManifestExportReferences = ({+ applicationAllFlatEntityMaps,+ allFlatEntityMaps,+ exportedObjectUniversalIdentifiers,+ resolvableFieldUniversalIdentifiers,+ canReferenceOtherApplicationsWorkflowActions,+}: {+ applicationAllFlatEntityMaps: Pick<+ AllFlatEntityMaps,+ | 'flatObjectMetadataMaps'+ | 'flatFieldMetadataMaps'+ | 'flatLogicFunctionMaps'+ | 'flatAgentMaps'+ >;+ allFlatEntityMaps: Pick<+ AllFlatEntityMaps,+ 'flatObjectMetadataMaps' | 'flatFieldMetadataMaps' | 'flatLogicFunctionMaps'+ >;+ exportedObjectUniversalIdentifiers: ReadonlySet<string>;+ resolvableFieldUniversalIdentifiers: ReadonlySet<string>;+ canReferenceOtherApplicationsWorkflowActions: boolean;+}): WorkflowManifestReferences => {+ const objectByUniversalIdentifier = new Map<+ string,+ WorkflowManifestObjectReference+ >();+ const fieldByUniversalIdentifier = new Map<+ string,+ WorkflowManifestFieldReference+ >();+ const logicFunctionIdByUniversalIdentifier = new Map<string, string>();+ const logicFunctionOutputSchemaByUniversalIdentifier = new Map<+ string,+ BaseOutputSchemaV2+ >();+ const agentIdByUniversalIdentifier = new Map<string, string>();+ const agentOutputSchemaByUniversalIdentifier = new Map<+ string,+ BaseOutputSchemaV2+ >();++ for (const flatObjectMetadata of Object.values(+ allFlatEntityMaps.flatObjectMetadataMaps.byUniversalIdentifier,+ ).filter(isDefined)) {+ const { universalIdentifier } = flatObjectMetadata;+ const isApplicationObject = isDefined(+ applicationAllFlatEntityMaps.flatObjectMetadataMaps.byUniversalIdentifier[+ universalIdentifier+ ],+ );++ if (+ !isApplicationObject ||+ exportedObjectUniversalIdentifiers.has(universalIdentifier)+ ) {+ objectByUniversalIdentifier.set(universalIdentifier, flatObjectMetadata);+ }+ }++ for (const flatFieldMetadata of Object.values(+ allFlatEntityMaps.flatFieldMetadataMaps.byUniversalIdentifier,+ ).filter(isDefined)) {+ const { universalIdentifier } = flatFieldMetadata;+ const isApplicationField = isDefined(+ applicationAllFlatEntityMaps.flatFieldMetadataMaps.byUniversalIdentifier[+ universalIdentifier+ ],+ );++ if (+ !isApplicationField ||+ resolvableFieldUniversalIdentifiers.has(universalIdentifier)+ ) {+ fieldByUniversalIdentifier.set(universalIdentifier, {+ ...flatFieldMetadata,+ objectUniversalIdentifier:+ flatFieldMetadata.objectMetadataUniversalIdentifier,+ });+ }+ }++ // Mirrors the sync rule: only the workspace custom application may call other apps' actions+ const referenceableFlatLogicFunctionMaps =+ canReferenceOtherApplicationsWorkflowActions+ ? allFlatEntityMaps.flatLogicFunctionMaps+ : applicationAllFlatEntityMaps.flatLogicFunctionMaps;++ for (const flatLogicFunction of Object.values(+ referenceableFlatLogicFunctionMaps.byUniversalIdentifier,+ ).filter(isDefined)) {+ if (isDefined(flatLogicFunction.deletedAt)) {+ continue;+ }++ const { universalIdentifier, workflowActionTriggerSettings } =+ flatLogicFunction;++ if (!isDefined(workflowActionTriggerSettings)) {+ continue;+ }++ logicFunctionIdByUniversalIdentifier.set(+ universalIdentifier,+ flatLogicFunction.id,+ );++ if (isDefined(workflowActionTriggerSettings.outputSchema)) {+ logicFunctionOutputSchemaByUniversalIdentifier.set(+ universalIdentifier,+ inputSchemaToOutputSchema(workflowActionTriggerSettings.outputSchema),+ );+ }+ }++ for (const flatAgent of Object.values(+ applicationAllFlatEntityMaps.flatAgentMaps.byUniversalIdentifier,+ ).filter(isDefined)) {+ agentIdByUniversalIdentifier.set(+ flatAgent.universalIdentifier,+ flatAgent.id,+ );+ agentOutputSchemaByUniversalIdentifier.set(+ flatAgent.universalIdentifier,+ computeAiAgentOutputSchema(flatAgent.responseFormat),+ );+ }++ return {+ objectByUniversalIdentifier,+ fieldByUniversalIdentifier,+ logicFunctionIdByUniversalIdentifier,+ logicFunctionOutputSchemaByUniversalIdentifier,+ agentIdByUniversalIdentifier,+ agentOutputSchemaByUniversalIdentifier,+ };+};diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-inverse-reference-resolvers.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-inverse-reference-resolvers.util.tsnew file mode 100644index 00000000000..7822855ab95--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-inverse-reference-resolvers.util.ts@@ -0,0 +1,189 @@+import { isDefined, isPlainObject } from 'twenty-shared/utils';++import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';+import { computeWorkflowWatchedFieldName } from 'src/engine/core-modules/application/application-manifest/utils/compute-workflow-watched-field-name.util';++const UNRESOLVED_REFERENCE = '';++const toObjectFieldKey = ({+ objectUniversalIdentifier,+ name,+}: {+ objectUniversalIdentifier: string;+ name: string;+}) => `${objectUniversalIdentifier}:${name}`;++const invertIdentifierMap = (+ idByUniversalIdentifier: ReadonlyMap<string, string> | undefined,+): Map<string, string> =>+ new Map(+ [...(idByUniversalIdentifier ?? new Map<string, string>())].map(+ ([universalIdentifier, id]) => [id, universalIdentifier],+ ),+ );++// Unresolved references become '' and record a reason, so converters report it once at the end.+export const buildWorkflowManifestInverseReferenceResolvers = (+ references: WorkflowManifestReferences,+) => {+ const unsupportedReasons: string[] = [];+ const objectUniversalIdentifierByNameSingular = new Map<string, string>();+ const fieldUniversalIdentifierById = new Map<string, string>();+ const fieldUniversalIdentifierByObjectFieldName = new Map<string, string>();+ const fieldUniversalIdentifierByWatchedFieldName = new Map<string, string>();+ const logicFunctionUniversalIdentifierById = invertIdentifierMap(+ references.logicFunctionIdByUniversalIdentifier,+ );+ const agentUniversalIdentifierById = invertIdentifierMap(+ references.agentIdByUniversalIdentifier,+ );++ for (const [+ universalIdentifier,+ object,+ ] of references.objectByUniversalIdentifier ?? []) {+ objectUniversalIdentifierByNameSingular.set(+ object.nameSingular,+ universalIdentifier,+ );+ }++ for (const [+ universalIdentifier,+ field,+ ] of references.fieldByUniversalIdentifier ?? []) {+ const { objectUniversalIdentifier } = field;+ const watchedFieldName = computeWorkflowWatchedFieldName(field);++ fieldUniversalIdentifierById.set(field.id, universalIdentifier);+ fieldUniversalIdentifierByObjectFieldName.set(+ toObjectFieldKey({ objectUniversalIdentifier, name: field.name }),+ universalIdentifier,+ );++ if (isDefined(watchedFieldName)) {+ fieldUniversalIdentifierByWatchedFieldName.set(+ toObjectFieldKey({ objectUniversalIdentifier, name: watchedFieldName }),+ universalIdentifier,+ );+ }+ }++ const markUnsupported = (reason: string): string => {+ unsupportedReasons.push(reason);++ return UNRESOLVED_REFERENCE;+ };++ const resolveOrMarkUnsupported = ({+ universalIdentifier,+ reason,+ }: {+ universalIdentifier: string | undefined;+ reason: string;+ }): string => universalIdentifier ?? markUnsupported(reason);++ const objectUniversalIdentifier = (nameSingular: unknown): string =>+ resolveOrMarkUnsupported({+ universalIdentifier:+ typeof nameSingular === 'string'+ ? objectUniversalIdentifierByNameSingular.get(nameSingular)+ : undefined,+ reason: 'workflow referencing an object that is not exported',+ });++ const fieldUniversalIdentifier = (fieldMetadataId: unknown): string =>+ resolveOrMarkUnsupported({+ universalIdentifier:+ typeof fieldMetadataId === 'string'+ ? fieldUniversalIdentifierById.get(fieldMetadataId)+ : undefined,+ reason: 'workflow referencing a field that is not exported',+ });++ const fieldUniversalIdentifierByName = ({+ objectUniversalIdentifier,+ fieldName,+ }: {+ objectUniversalIdentifier: string;+ fieldName: unknown;+ }): string =>+ resolveOrMarkUnsupported({+ universalIdentifier:+ typeof fieldName === 'string'+ ? fieldUniversalIdentifierByObjectFieldName.get(+ toObjectFieldKey({ objectUniversalIdentifier, name: fieldName }),+ )+ : undefined,+ reason: 'workflow referencing a field that is not exported',+ });++ const watchedFieldUniversalIdentifier = ({+ objectUniversalIdentifier,+ watchedFieldName,+ }: {+ objectUniversalIdentifier: string;+ watchedFieldName: unknown;+ }): string =>+ resolveOrMarkUnsupported({+ universalIdentifier:+ typeof watchedFieldName === 'string'+ ? fieldUniversalIdentifierByWatchedFieldName.get(+ toObjectFieldKey({+ objectUniversalIdentifier,+ name: watchedFieldName,+ }),+ )+ : undefined,+ reason: 'workflow watching a field that is not exported',+ });++ const logicFunctionUniversalIdentifier = (logicFunctionId: unknown): string =>+ resolveOrMarkUnsupported({+ universalIdentifier:+ typeof logicFunctionId === 'string'+ ? logicFunctionUniversalIdentifierById.get(logicFunctionId)+ : undefined,+ reason:+ 'workflow step on a logic function that is not a workflow action of this application',+ });++ const agentUniversalIdentifier = (agentId: unknown): string =>+ resolveOrMarkUnsupported({+ universalIdentifier:+ typeof agentId === 'string'+ ? agentUniversalIdentifierById.get(agentId)+ : undefined,+ reason: 'workflow step on an agent of another application',+ });++ const fieldReference = (+ reference: unknown,+ ): Record<string, unknown> | undefined => {+ if (!isPlainObject(reference)) {+ return undefined;+ }++ const { fieldMetadataId, ...rest } = reference;++ return isDefined(fieldMetadataId)+ ? {+ ...rest,+ fieldMetadataUniversalIdentifier:+ fieldUniversalIdentifier(fieldMetadataId),+ }+ : rest;+ };++ return {+ objectUniversalIdentifier,+ fieldUniversalIdentifier,+ fieldReference,+ fieldUniversalIdentifierByName,+ watchedFieldUniversalIdentifier,+ logicFunctionUniversalIdentifier,+ agentUniversalIdentifier,+ markUnsupported,+ getUnsupportedReason: (): string | undefined => unsupportedReasons[0],+ };+};diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-watched-field-name.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-watched-field-name.util.tsnew file mode 100644index 00000000000..bc1cba54e5b--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-watched-field-name.util.ts@@ -0,0 +1,31 @@+import { FieldMetadataType, RelationType } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { type WorkflowManifestFieldReference } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';+import { computeMorphOrRelationFieldJoinColumnName } from 'src/engine/metadata-modules/field-metadata/utils/compute-morph-or-relation-field-join-column-name.util';++// Updates only report relations to a single record, through their join column.+export const computeWorkflowWatchedFieldName = (+ field: Pick<+ WorkflowManifestFieldReference,+ 'name' | 'type' | 'universalSettings'+ >,+): string | undefined => {+ if (+ field.type !== FieldMetadataType.RELATION &&+ field.type !== FieldMetadataType.MORPH_RELATION+ ) {+ return field.name;+ }++ const isManyToOneRelation =+ isDefined(field.universalSettings) &&+ 'relationType' in field.universalSettings &&+ field.universalSettings.relationType === RelationType.MANY_TO_ONE;++ if (!isManyToOneRelation) {+ return undefined;+ }++ return computeMorphOrRelationFieldJoinColumnName({ name: field.name });+};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.tsnew file mode 100644index 00000000000..f91a64aac1d--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/reconstruct-workflows-manifest.util.ts@@ -0,0 +1,145 @@+import {+ getWorkflowVersionUniversalIdentifier,+ type WorkflowManifest,+} from 'twenty-shared/application';+import { WorkflowVisibility } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { WORKFLOW_CHANGED_IN_BUILDER_REASON } from 'src/engine/core-modules/application/application-manifest/constants/workflow-changed-in-builder-reason.constant';+import { fromFlatWorkflowToWorkflowManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-flat-workflow-to-workflow-manifest.util';+import { type ApplicationExportCoverageEntry } from 'src/engine/core-modules/application/application-manifest/types/application-export.type';+import { buildExportedCoverageEntry } from 'src/engine/core-modules/application/application-manifest/utils/build-exported-coverage-entry.util';+import { buildWorkflowManifestExportReferences } from 'src/engine/core-modules/application/application-manifest/utils/build-workflow-manifest-export-references.util';+import { sortFlatEntitiesByUniversalIdentifier } from 'src/engine/core-modules/application/application-manifest/utils/sort-flat-entities-by-universal-identifier.util';+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 { 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 = ({+ flatWorkflow,+ allFlatEntityMaps,+}: {+ flatWorkflow: Pick<+ FlatWorkflow,+ | 'applicationUniversalIdentifier'+ | 'universalIdentifier'+ | 'lastPublishedCoreWorkflowVersionId'+ >;+ allFlatEntityMaps: Pick<AllFlatEntityMaps, 'flatWorkflowVersionMaps'>;+}): FlatWorkflowVersion | undefined => {+ const flatWorkflowVersion =+ allFlatEntityMaps.flatWorkflowVersionMaps.byUniversalIdentifier[+ getWorkflowVersionUniversalIdentifier({+ applicationUniversalIdentifier:+ flatWorkflow.applicationUniversalIdentifier,+ workflowUniversalIdentifier: flatWorkflow.universalIdentifier,+ })+ ];++ return isDefined(flatWorkflowVersion) &&+ flatWorkflowVersion.status === WorkflowVersionStatus.ACTIVE &&+ flatWorkflowVersion.id === flatWorkflow.lastPublishedCoreWorkflowVersionId+ ? flatWorkflowVersion+ : undefined;+};++export const reconstructWorkflowsManifest = ({+ applicationAllFlatEntityMaps,+ allFlatEntityMaps,+ exportedObjectUniversalIdentifiers,+ resolvableFieldUniversalIdentifiers,+ canReferenceOtherApplicationsWorkflowActions,+}: {+ applicationAllFlatEntityMaps: AllFlatEntityMaps;+ allFlatEntityMaps: AllFlatEntityMaps;+ exportedObjectUniversalIdentifiers: ReadonlySet<string>;+ resolvableFieldUniversalIdentifiers: ReadonlySet<string>;+ canReferenceOtherApplicationsWorkflowActions: boolean;+}): {+ workflows: WorkflowManifest[];+ coverage: ApplicationExportCoverageEntry[];+} => {+ const workflows: WorkflowManifest[] = [];+ const coverage: ApplicationExportCoverageEntry[] = [];+ const references = buildWorkflowManifestExportReferences({+ applicationAllFlatEntityMaps,+ allFlatEntityMaps,+ exportedObjectUniversalIdentifiers,+ resolvableFieldUniversalIdentifiers,+ canReferenceOtherApplicationsWorkflowActions,+ });++ const getExclusionReason = (flatWorkflow: FlatWorkflow) => {+ if (flatWorkflow.isSystem) {+ return 'system workflow';+ }++ return flatWorkflow.visibility === WorkflowVisibility.PRIVATE+ ? 'private workflow'+ : undefined;+ };++ const convertFlatWorkflow = (+ flatWorkflow: FlatWorkflow,+ ): { manifest: WorkflowManifest } | { reason: string } => {+ if (isDefined(flatWorkflow.workspaceWorkflowId)) {+ return { reason: 'workflow created in the workspace' };+ }++ const flatWorkflowVersion = findSyncedFlatWorkflowVersion({+ flatWorkflow,+ allFlatEntityMaps,+ });++ if (!isDefined(flatWorkflowVersion)) {+ return { reason: WORKFLOW_CHANGED_IN_BUILDER_REASON };+ }++ return fromFlatWorkflowToWorkflowManifest({+ flatWorkflow,+ flatWorkflowVersion,+ references,+ });+ };++ for (const flatWorkflow of sortFlatEntitiesByUniversalIdentifier(+ applicationAllFlatEntityMaps.flatWorkflowMaps,+ )) {+ const { universalIdentifier } = flatWorkflow;+ const exclusionReason = getExclusionReason(flatWorkflow);++ if (isDefined(exclusionReason)) {+ coverage.push({+ metadataName: 'workflow',+ universalIdentifier,+ status: ApplicationExportCoverageStatus.EXCLUDED,+ reason: exclusionReason,+ });+ continue;+ }++ const conversion = convertFlatWorkflow(flatWorkflow);++ if ('reason' in conversion) {+ coverage.push({+ metadataName: 'workflow',+ universalIdentifier,+ status: ApplicationExportCoverageStatus.UNSUPPORTED,+ reason: conversion.reason,+ });+ continue;+ }++ coverage.push(+ buildExportedCoverageEntry({+ metadataName: 'workflow',+ flatEntity: flatWorkflow,+ }),+ );+ workflows.push(conversion.manifest);+ }++ return { workflows, coverage };+};diff --git a/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/successful-export-application-data-model.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/successful-export-application-data-model.integration-spec.ts.snapindex ff991f6bdfc..e69f02b4749 100644--- a/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/successful-export-application-data-model.integration-spec.ts.snap+++ b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/successful-export-application-data-model.integration-spec.ts.snap@@ -1268,5 +1268,6 @@ exports[`Application export - data model exports the whole application as a stab"visibility": "WORKSPACE",},],+ "workflows": [],}`;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.tsindex 428bb5d4f84..012b9c496fc 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@@ -29,6 +29,8 @@ import {getSystemRelationFieldUniversalIdentifier,getSystemViewFieldUniversalIdentifier,getSystemViewUniversalIdentifier,+ getWorkflowCommandMenuItemUniversalIdentifier,+ getWorkflowVersionUniversalIdentifier,type NavigationMenuItemManifest,type ObjectManifest,type PageLayoutManifest,@@ -39,6 +41,7 @@ import {type TranslationsManifest,TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,type ViewManifest,+ type WorkflowManifest,} from 'twenty-shared/application';import {PermissionFlagType,@@ -55,6 +58,7 @@ import {RelationType,RowLevelPermissionPredicateGroupLogicalOperator,RowLevelPermissionPredicateOperand,+ StepLogicalOperator,ViewFilterGroupLogicalOperator,ViewFilterOperand,ViewSortDirection,@@ -1416,3 +1420,321 @@ describe('Application export - data model', () => {}}, 60000);});++const WORKFLOW_TEST_APP_ID = '7e3d1c2b-0100-4a7b-8c9d-0e1f2a3b4c5d';+const WORKFLOW_TEST_ROLE_ID = '7e3d1c2b-0101-4a7b-8c9d-0e1f2a3b4c5d';+const INCIDENT_OBJECT_ID = '7e3d1c2b-0102-4a7b-8c9d-0e1f2a3b4c5d';+const INCIDENT_SEVERITY_FIELD_ID = '7e3d1c2b-0103-4a7b-8c9d-0e1f2a3b4c5d';+const ESCALATION_WORKFLOW_ID = '7e3d1c2b-0110-4a7b-8c9d-0e1f2a3b4c5d';+const NOTIFY_WORKFLOW_ID = '7e3d1c2b-0111-4a7b-8c9d-0e1f2a3b4c5d';+const NIGHTLY_WORKFLOW_ID = '7e3d1c2b-0112-4a7b-8c9d-0e1f2a3b4c5d';+const INTAKE_WORKFLOW_ID = '7e3d1c2b-0113-4a7b-8c9d-0e1f2a3b4c5d';+const workflowNodeIdentifier = (suffix: number) =>+ `7e3d1c2b-${(200 + suffix).toString().padStart(4, '0')}-4a7b-8c9d-0e1f2a3b4c5d`;++const SEVERITY_STEP_FILTERS = {+ stepFilterGroups: [{ id: 'group', logicalOperator: StepLogicalOperator.AND }],+ stepFilters: [+ {+ id: 'severity',+ type: 'TEXT',+ stepOutputKey: '{{trigger.properties.after.severity}}',+ operand: ViewFilterOperand.IS,+ value: 'high',+ stepFilterGroupId: 'group',+ fieldMetadataUniversalIdentifier: INCIDENT_SEVERITY_FIELD_ID,+ },+ ],+};++const EXPORTED_WORKFLOWS: WorkflowManifest[] = [+ {+ universalIdentifier: ESCALATION_WORKFLOW_ID,+ name: 'Escalate severe incidents',+ version: {+ trigger: {+ universalIdentifier: workflowNodeIdentifier(0),+ type: 'DATABASE_EVENT',+ nextStepIds: [workflowNodeIdentifier(1)],+ settings: {+ objectUniversalIdentifier: INCIDENT_OBJECT_ID,+ action: 'updated',+ fieldUniversalIdentifiers: [INCIDENT_SEVERITY_FIELD_ID],+ filter: SEVERITY_STEP_FILTERS,+ },+ },+ steps: [+ {+ universalIdentifier: workflowNodeIdentifier(1),+ name: 'Find severe incidents',+ type: 'FIND_RECORDS',+ nextStepIds: [workflowNodeIdentifier(2)],+ input: {+ objectUniversalIdentifier: INCIDENT_OBJECT_ID,+ limit: 5,+ filter: {+ recordFilters: [+ {+ fieldMetadataUniversalIdentifier: INCIDENT_SEVERITY_FIELD_ID,+ operand: ViewFilterOperand.IS,+ value: 'high',+ },+ ],+ },+ orderBy: {+ recordSorts: [+ {+ fieldMetadataUniversalIdentifier: INCIDENT_SEVERITY_FIELD_ID,+ direction: 'DESC',+ },+ ],+ },+ },+ },+ {+ universalIdentifier: workflowNodeIdentifier(2),+ name: 'Is severe',+ type: 'IF_ELSE',+ nextStepIds: [],+ input: {+ ...SEVERITY_STEP_FILTERS,+ branches: [+ {+ id: 'severe',+ nextStepIds: [workflowNodeIdentifier(3)],+ filterGroupId: 'group',+ },+ { id: 'otherwise', nextStepIds: [workflowNodeIdentifier(4)] },+ ],+ },+ },+ {+ universalIdentifier: workflowNodeIdentifier(3),+ name: 'Open a company follow-up',+ type: 'CREATE_RECORD',+ nextStepIds: [],+ input: {+ objectUniversalIdentifier:+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company,+ objectRecord: { name: 'Escalation' },+ },+ },+ {+ universalIdentifier: workflowNodeIdentifier(4),+ name: 'Nothing to do',+ type: 'EMPTY',+ nextStepIds: [],+ input: {},+ },+ ],+ },+ },+ {+ universalIdentifier: NOTIFY_WORKFLOW_ID,+ name: 'Notify on-call',+ version: {+ trigger: {+ universalIdentifier: workflowNodeIdentifier(10),+ type: 'MANUAL',+ nextStepIds: [workflowNodeIdentifier(11)],+ settings: {+ availability: {+ type: 'SINGLE_RECORD',+ objectUniversalIdentifier: INCIDENT_OBJECT_ID,+ },+ icon: 'IconBell',+ isPinned: true,+ },+ },+ steps: [+ {+ universalIdentifier: workflowNodeIdentifier(11),+ name: 'Call the pager',+ type: 'HTTP_REQUEST',+ nextStepIds: [],+ position: { x: 120, y: 240 },+ errorHandlingOptions: {+ retryOnFailure: { value: 2 },+ continueOnFailure: { value: true },+ },+ input: {+ method: 'POST',+ url: 'https://example.com/pager',+ body: { incident: '{{trigger.record.id}}' },+ },+ },+ ],+ },+ },+ {+ universalIdentifier: NIGHTLY_WORKFLOW_ID,+ name: 'Nightly digest',+ version: {+ trigger: {+ universalIdentifier: workflowNodeIdentifier(20),+ type: 'CRON',+ nextStepIds: [workflowNodeIdentifier(21)],+ settings: { type: 'DAYS', schedule: { day: 1, hour: 3, minute: 15 } },+ },+ steps: [+ {+ universalIdentifier: workflowNodeIdentifier(21),+ name: 'Wait',+ type: 'DELAY',+ nextStepIds: [],+ input: { delayType: 'DURATION', duration: { minutes: 5 } },+ },+ ],+ },+ },+ {+ universalIdentifier: INTAKE_WORKFLOW_ID,+ name: 'Incident intake',+ version: {+ trigger: {+ universalIdentifier: workflowNodeIdentifier(30),+ type: 'WEBHOOK',+ nextStepIds: [workflowNodeIdentifier(31)],+ settings: {+ httpMethod: 'POST',+ expectedBody: { severity: 'high' },+ },+ },+ steps: [+ {+ universalIdentifier: workflowNodeIdentifier(31),+ name: 'Review',+ type: 'FORM',+ nextStepIds: [],+ input: [+ {+ id: 'summary',+ name: 'summary',+ label: 'Summary',+ type: FieldMetadataType.TEXT,+ },+ {+ id: 'incident',+ name: 'incident',+ label: 'Incident',+ type: 'RECORD',+ settings: { objectUniversalIdentifier: INCIDENT_OBJECT_ID },+ },+ ],+ },+ ],+ },+ },+];++const workflowsManifest = buildBaseManifest({+ appId: WORKFLOW_TEST_APP_ID,+ roleId: WORKFLOW_TEST_ROLE_ID,+ overrides: {+ objects: [+ buildDefaultObjectManifest({+ universalIdentifier: INCIDENT_OBJECT_ID,+ nameSingular: 'exportIncident',+ namePlural: 'exportIncidents',+ labelSingular: 'Incident',+ labelPlural: 'Incidents',+ applicationUniversalIdentifier: WORKFLOW_TEST_APP_ID,+ additionalFields: [+ {+ universalIdentifier: INCIDENT_SEVERITY_FIELD_ID,+ name: 'severity',+ label: 'Severity',+ type: FieldMetadataType.TEXT,+ },+ ],+ }),+ ],+ workflows: EXPORTED_WORKFLOWS,+ },+});++describe('Application export - workflows', () => {+ beforeAll(async () => {+ await cleanupApplicationAndAppRegistration({+ applicationUniversalIdentifier: WORKFLOW_TEST_APP_ID,+ });+ await setupApplicationForSync({+ applicationUniversalIdentifier: WORKFLOW_TEST_APP_ID,+ name: 'Export Workflows Test Application',+ description: 'App for testing the workflow export',+ sourcePath: 'export-workflows',+ });++ await syncApplication({+ manifest: workflowsManifest,+ expectToFail: false,+ });+ }, 60000);++ afterAll(async () => {+ await cleanupApplicationAndAppRegistration({+ applicationUniversalIdentifier: WORKFLOW_TEST_APP_ID,+ });+ });++ it('exports the synced workflows as they were declared', async () => {+ const { data, errors } = await exportApplication({+ universalIdentifier: WORKFLOW_TEST_APP_ID,+ expectToFail: false,+ });++ expect(errors).toBeUndefined();++ const { manifest: exportedManifest, coverage } = data.exportApplication;+ const statusOf = (universalIdentifier: string) =>+ coverage.find(+ (entry) => entry.universalIdentifier === universalIdentifier,+ )?.status;++ expect(exportedManifest.workflows).toEqual(+ [...EXPORTED_WORKFLOWS].sort((left, right) =>+ left.universalIdentifier.localeCompare(right.universalIdentifier),+ ),+ );++ for (const { universalIdentifier } of EXPORTED_WORKFLOWS) {+ expect(statusOf(universalIdentifier)).toBe(+ ApplicationExportCoverageStatus.EXPORTED,+ );+ expect(+ statusOf(+ getWorkflowVersionUniversalIdentifier({+ applicationUniversalIdentifier: WORKFLOW_TEST_APP_ID,+ workflowUniversalIdentifier: universalIdentifier,+ }),+ ),+ ).toBe(ApplicationExportCoverageStatus.ENGINE_DERIVED);+ }++ expect(+ statusOf(+ getWorkflowCommandMenuItemUniversalIdentifier({+ applicationUniversalIdentifier: WORKFLOW_TEST_APP_ID,+ workflowUniversalIdentifier: NOTIFY_WORKFLOW_ID,+ }),+ ),+ ).toBe(ApplicationExportCoverageStatus.ENGINE_DERIVED);+ }, 60000);++ it('round-trips the exported workflows through an additive dry-run sync without any action', async () => {+ const { data } = await exportApplication({+ universalIdentifier: WORKFLOW_TEST_APP_ID,+ expectToFail: false,+ });++ const dryRun = await syncApplication({+ manifest: data.exportApplication.manifest,+ dryRun: true,+ inferDeletionFromMissingEntities: false,+ expectToFail: false,+ });++ expect(dryRun.errors).toBeUndefined();+ expect(dryRun.data.syncApplication.actions).toEqual([]);+ }, 60000);+});