The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Round-trip workflows built in the workflow builder through the manifest (#29053)
Félix Malfaite51ef6261e06
diff --git a/packages/twenty-agent-skills/references/develop-app/logic.md b/packages/twenty-agent-skills/references/develop-app/logic.mdindex 734d72641a2..98fc01a4df0 100644--- a/packages/twenty-agent-skills/references/develop-app/logic.md+++ b/packages/twenty-agent-skills/references/develop-app/logic.md@@ -127,7 +127,7 @@ To let the workspace's AI call a remote MCP server (Streamable HTTP) without syn## Post-Install Hooks-Use `definePostInstallLogicFunction` for records that must exist on install — default workflows, views, roles, or seeded reference data. Do not implement this as runtime first-run code.+Use `definePostInstallLogicFunction` for records that must exist on install — views, roles, or seeded reference data. Ship workflows with `defineWorkflow` (see `workflows.md`). Do not implement this as runtime first-run code.Post-install hook files live alongside other logic functions (typically `src/logic-functions/<name>.post-install.ts`). Kebab-case filename, one export per file.diff --git a/packages/twenty-agent-skills/references/develop-app/workflows.md b/packages/twenty-agent-skills/references/develop-app/workflows.mdindex 6f53d36f05e..57d94c3e741 100644--- a/packages/twenty-agent-skills/references/develop-app/workflows.md+++ b/packages/twenty-agent-skills/references/develop-app/workflows.md@@ -1,15 +1,25 @@# Workflows-Use when the app needs to ship a manual workflow on install, or when a logic function should be invocable from the workflow builder.+Use when the app needs to ship a workflow, or when a logic function should be invocable from the workflow builder.See `logic.md` for post-install hooks. See `app-structure.md` for source layout.## Mental Model-Declare app workflows with `defineWorkflow` from `twenty-sdk/define`: one call per workflow, holding a trigger and its steps. `twenty app pull` writes workflows in this form.+Declare app workflows with `defineWorkflow` from `twenty-sdk/define`: one call per workflow, holding a trigger and its steps. Install creates it active; installing a new app version updates it in place. Users can't edit an installed workflow — they duplicate it.Workflows created at runtime through the workspace API are a `Workflow` plus at least one `WorkflowVersion`. Creating a `Workflow` auto-creates its draft `v1`; never create a `WorkflowVersion` directly.+## defineWorkflow++- The workflow and each step need a stable `universalIdentifier`. The trigger's is optional.+- `nextStepIds` wires the graph: the trigger points to the first steps, each step to the steps after it.+- Trigger types: `MANUAL`, `CRON`, `DATABASE_EVENT`, `WEBHOOK`. Step types exclude the builder's `CODE` — use `LOGIC_FUNCTION`.+- Reference objects, fields, logic functions and agents by universal identifier, never by name or id.+- Triggers take optional `name`, `position` and `outputSchema`; steps take optional `position` and `outputSchema`. They only shape the builder view. Omit them to get the derived defaults.+- `position: null` means no position. `outputSchema: {}` means an empty schema; omit `outputSchema` to derive it.+- `twenty app pull` on the workspace Custom application writes builder workflows in this form, keeping the builder's trigger name, positions and output schemas.+## Email and Calendar Steps- `SEND_EMAIL`, `DRAFT_EMAIL` and `CREATE_CALENDAR_EVENT` name their account with exactly one of `connectedAccountId` or `connectedAccountHandle`.@@ -22,9 +32,9 @@ Workflows created at runtime through the workspace API are a `Workflow` plus at- The selected record is the trigger payload — no wrapping `record` field.- Reference fields with `{{trigger.<field>}}`. Do not use `{{trigger.record.<field>}}`.-## Lifecycle+## Lifecycle Through the Workspace API-Always: create → configure draft → activate. Never publish a draft directly.+Only for workflows created at runtime, e.g. from a post-install hook, instead of `defineWorkflow`. Always: create → configure draft → activate. Never publish a draft directly.1. Find or create the `Workflow` by stable name or slug. `createWorkflow` produces the draft `v1`.2. Set the trigger on the draft via `updateWorkflowVersion`.diff --git a/packages/twenty-agent-skills/skills/develop-app/SKILL.md b/packages/twenty-agent-skills/skills/develop-app/SKILL.mdindex bbf932b5a63..25e46a6504d 100644--- a/packages/twenty-agent-skills/skills/develop-app/SKILL.md+++ b/packages/twenty-agent-skills/skills/develop-app/SKILL.md@@ -106,7 +106,7 @@ Read the smallest reference that matches the requested entity work:- Full-page custom UI and standalone page patterns: `../../references/develop-app/standalone-pages.md`- Front component source, Twenty UI imports, data hooks, runtime imports, and browser verification: `../../references/develop-app/front-components.md`- Logic functions, skills, agents, post-install hooks, and connection providers: `../../references/develop-app/logic.md`-- Workflows, manual triggers, draft/activate lifecycle, and seeder pitfalls: `../../references/develop-app/workflows.md`+- Workflows with `defineWorkflow`, manual triggers, the runtime draft/activate lifecycle, and seeder pitfalls: `../../references/develop-app/workflows.md`- Tests — what to cover and where to put the files: `../../references/develop-app/tests.md`- App file structure and entity validation checklist: `../../references/develop-app/app-structure.md`- Detailed front component UI design: `../../references/design/front-component-ui.md`diff --git a/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx b/packages/twenty-docs/developers/extend/apps/logic/workflows.mdxindex df09dd7d319..e6999e16819 100644--- a/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx+++ b/packages/twenty-docs/developers/extend/apps/logic/workflows.mdx@@ -67,7 +67,7 @@ export default defineWorkflow({```Key points:-- The workflow, its trigger and each step need their own `universalIdentifier`. Keep them stable across releases: they are how Twenty matches the installed workflow on the next install.+- The workflow and each step need their own `universalIdentifier`, and the trigger can have one. Keep them stable across releases: they are how Twenty matches the installed workflow on the next install.- `nextStepIds` wires the graph. The trigger points to the first steps, and each step points to the steps that run after it.- A step reads earlier output with `{{trigger.<path>}}` or `{{<step universalIdentifier>.<path>}}`.- The build validates the whole definition: unsupported trigger or step types, broken step links and references to unknown steps fail it.@@ -93,6 +93,8 @@ A reference Twenty can't resolve fails the install.A manual workflow without `availability` gets no command menu entry.+Every trigger also takes optional `name`, `position` and `outputSchema`, which only shape how the workflow looks in the builder. Without them, Twenty uses a name such as `Manual trigger`, places the trigger at the top of the canvas and computes the output schema from the settings.+A webhook workflow listens on `https://<your-twenty-domain>/webhooks/workflows/<workspaceId>/<workflowId>`, where `workflowId` is the id of the installed workflow. The request body is available as `{{trigger.<path>}}`.## Steps@@ -121,7 +123,8 @@ Their inputs match the steps of the [workflow builder](/user-guide/workflows/cap## Workflows of the workspace Custom applicationThe workspace Custom application owns the workflows built in the workflow builder, and code is as authoritative for them as the builder:-- `twenty app pull` writes each one from its active version, the one the builder last published. A workflow whose active version uses settings a `defineWorkflow()` file can't express, such as a Code step or a trigger the builder renamed, is reported and left in place.+- `twenty app pull` writes each one from its active version, the one the builder last published. A workflow whose active version uses settings a `defineWorkflow()` file can't express, such as a Code step, is reported and left in place.+- A pulled workflow keeps what the builder stored: a trigger without a `universalIdentifier`, the trigger's builder name, a `position` of `null` for a node the builder never placed, and an `outputSchema` that differs from the computed one. These fields need twenty-sdk 2.53.0 or later, applied to a server on 2.53.0 or later: older versions reject them as unknown keys.- `twenty app apply` publishes like the builder. A workflow whose definition matches its active version is left alone. Otherwise the active version is archived and the definition becomes a new active version, so past runs keep the version they ran.- Users keep editing these workflows in the builder, and the next pull brings their changes back.diff --git a/packages/twenty-front/src/modules/workflow/workflow-trigger/constants/DatabaseTriggerDefaultLabel.ts b/packages/twenty-front/src/modules/workflow/workflow-trigger/constants/DatabaseTriggerDefaultLabel.tsindex ecdbc3fe532..31371440d62 100644--- a/packages/twenty-front/src/modules/workflow/workflow-trigger/constants/DatabaseTriggerDefaultLabel.ts+++ b/packages/twenty-front/src/modules/workflow/workflow-trigger/constants/DatabaseTriggerDefaultLabel.ts@@ -1,6 +1,11 @@-export enum DatabaseTriggerDefaultLabel {- RECORD_IS_CREATED = 'Record is created',- RECORD_IS_UPDATED = 'Record is updated',- RECORD_IS_DELETED = 'Record is deleted',- RECORD_UPSERTED = 'Record is created or updated',-}+import { WORKFLOW_TRIGGER_DEFAULT_NAMES } from 'twenty-shared/workflow';++export const DatabaseTriggerDefaultLabel = {+ RECORD_IS_CREATED: WORKFLOW_TRIGGER_DEFAULT_NAMES.DATABASE_EVENT.created,+ RECORD_IS_UPDATED: WORKFLOW_TRIGGER_DEFAULT_NAMES.DATABASE_EVENT.updated,+ RECORD_IS_DELETED: WORKFLOW_TRIGGER_DEFAULT_NAMES.DATABASE_EVENT.deleted,+ RECORD_UPSERTED: WORKFLOW_TRIGGER_DEFAULT_NAMES.DATABASE_EVENT.upserted,+} as const;++export type DatabaseTriggerDefaultLabel =+ (typeof DatabaseTriggerDefaultLabel)[keyof typeof DatabaseTriggerDefaultLabel];diff --git a/packages/twenty-front/src/modules/workflow/workflow-trigger/constants/triggers/CronTrigger.ts b/packages/twenty-front/src/modules/workflow/workflow-trigger/constants/triggers/CronTrigger.tsindex 30de35276ba..57415147e0d 100644--- a/packages/twenty-front/src/modules/workflow/workflow-trigger/constants/triggers/CronTrigger.ts+++ b/packages/twenty-front/src/modules/workflow/workflow-trigger/constants/triggers/CronTrigger.ts@@ -1,12 +1,12 @@import { type WorkflowTriggerType } from '@/workflow/types/Workflow';-import { doNotTranslate } from 'twenty-shared/i18n';+import { WORKFLOW_TRIGGER_DEFAULT_NAMES } from 'twenty-shared/workflow';export const CRON_TRIGGER: {defaultLabel: string;type: WorkflowTriggerType;icon: string;} = {- defaultLabel: doNotTranslate('On a schedule'),+ defaultLabel: WORKFLOW_TRIGGER_DEFAULT_NAMES.CRON,type: 'CRON',icon: 'IconClock',};diff --git a/packages/twenty-front/src/modules/workflow/workflow-trigger/constants/triggers/WebhookTrigger.ts b/packages/twenty-front/src/modules/workflow/workflow-trigger/constants/triggers/WebhookTrigger.tsindex aeeec2c5b99..74ae78a7acd 100644--- a/packages/twenty-front/src/modules/workflow/workflow-trigger/constants/triggers/WebhookTrigger.ts+++ b/packages/twenty-front/src/modules/workflow/workflow-trigger/constants/triggers/WebhookTrigger.ts@@ -1,12 +1,12 @@import { type WorkflowTriggerType } from '@/workflow/types/Workflow';-import { doNotTranslate } from 'twenty-shared/i18n';+import { WORKFLOW_TRIGGER_DEFAULT_NAMES } from 'twenty-shared/workflow';export const WEBHOOK_TRIGGER: {defaultLabel: string;type: WorkflowTriggerType;icon: string;} = {- defaultLabel: doNotTranslate('Webhook'),+ defaultLabel: WORKFLOW_TRIGGER_DEFAULT_NAMES.WEBHOOK,type: 'WEBHOOK',icon: 'IconWebhook',};diff --git a/packages/twenty-sdk/src/sdk/define/workflows/__tests__/define-workflow.spec.ts b/packages/twenty-sdk/src/sdk/define/workflows/__tests__/define-workflow.spec.tsindex 5a4803e1fae..79d0ff27c7a 100644--- a/packages/twenty-sdk/src/sdk/define/workflows/__tests__/define-workflow.spec.ts+++ b/packages/twenty-sdk/src/sdk/define/workflows/__tests__/define-workflow.spec.ts@@ -61,6 +61,25 @@ describe('defineWorkflow', () => {});});+ it('accepts the trigger state a workflow built in the workflow builder pulls with', () => {+ const { universalIdentifier: _universalIdentifier, ...trigger } =+ workflow.version.trigger;+ const pulled = {+ ...workflow,+ version: {+ ...workflow.version,+ trigger: {+ ...trigger,+ name: 'Launch manually',+ position: null,+ outputSchema: {},+ },+ },+ };++ expect(defineWorkflow(pulled).errors).toEqual([]);+ });+it('accepts a workflow flagged as system', () => {const systemWorkflow = { ...workflow, isSystem: true };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.tsindex 38c5673d832..a8da2e0ad94 100644--- 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.ts@@ -12,10 +12,14 @@ import {ViewFilterOperand,} from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';-import { WorkflowActionType } from 'twenty-shared/workflow';+import {+ type BaseOutputSchemaV2,+ 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 StoredWorkflowNode } from 'src/engine/core-modules/application/application-manifest/types/stored-workflow-version-definition.type';import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';import { type ConnectedAccountForWorkflowStepResolution } from 'src/engine/metadata-modules/connected-account/types/connected-account-for-workflow-step-resolution.type';import { type FlatWorkflow } from 'src/engine/metadata-modules/flat-workflow/types/flat-workflow.type';@@ -813,7 +817,7 @@ describe('fromFlatWorkflowToWorkflowManifest', () => {throw new Error('Expected the synced version to have a trigger');}- Object.assign(trigger, { name: 'Renamed in the builder' });+ Object.assign(trigger, { propertyNoManifestFieldHolds: true });expect(exportWorkflow(synced)).toEqual({reason: 'workflow changed in the workflow builder',@@ -821,3 +825,343 @@ describe('fromFlatWorkflowToWorkflowManifest', () => {});});});++describe('fromFlatWorkflowToWorkflowManifest on versions built in the workflow builder', () => {+ const DECLARED_OUTPUT_SCHEMA: BaseOutputSchemaV2 = {+ ok: { isLeaf: true, type: 'boolean', label: 'ok', value: true },+ };+ const builderReferences: WorkflowManifestReferences = {+ ...references,+ logicFunctionOutputSchemaByUniversalIdentifier: new Map([+ [FUNCTION_ID, DECLARED_OUTPUT_SCHEMA],+ ]),+ };+ const BUILDER_ERROR_HANDLING_OPTIONS = {+ continueOnFailure: { value: false },+ retryOnFailure: { value: 0 },+ };++ const recordCreatedTrigger = (+ overrides: Partial<StoredWorkflowNode> = {},+ ): StoredWorkflowNode => ({+ name: 'Record is created',+ type: 'DATABASE_EVENT',+ position: { x: 0, y: 0 },+ settings: { eventName: 'ticket.created', outputSchema: {} },+ nextStepIds: [STEP_ID],+ ...overrides,+ });++ const createRecordStep = (+ overrides: Partial<StoredWorkflowNode> = {},+ ): StoredWorkflowNode => ({+ id: STEP_ID,+ name: 'Create Record',+ type: 'CREATE_RECORD',+ valid: false,+ position: { x: 0, y: 180 },+ nextStepIds: [],+ settings: {+ outputSchema: {},+ errorHandlingOptions: BUILDER_ERROR_HANDLING_OPTIONS,+ input: { objectName: 'ticket', objectRecord: { name: 'Ticket' } },+ },+ ...overrides,+ });++ const exportBuilderVersion = ({+ triggers,+ steps,+ }: {+ triggers: StoredWorkflowNode[];+ steps: StoredWorkflowNode[];+ }) => {+ const synced = syncWorkflow(buildWorkflow({}));+ // The entity types its jsonb as the current builder writes it; rows also hold older shapes+ const flatWorkflowVersion = {+ ...synced.flatWorkflowVersion,+ triggers,+ steps,+ } as FlatWorkflowVersion;+ const result = fromFlatWorkflowToWorkflowManifest({+ flatWorkflow: synced.flatWorkflow,+ flatWorkflowVersion,+ references: builderReferences,+ });++ if ('reason' in result) {+ throw new Error(result.reason);+ }++ const applied = fromWorkflowManifestToUniversalFlatWorkflowOrThrow({+ manifest: result.manifest,+ applicationUniversalIdentifier: APPLICATION_ID,+ existingWorkflow: synced.flatWorkflow,+ activeVersion: flatWorkflowVersion,+ isWorkspaceCustomApplication: true,+ now: '2026-10-27T00:00:00.000Z',+ ...builderReferences,+ });++ // apply keeps the active version as it is, so it produces no action+ expect(applied.flatUniversalWorkflowVersion?.id).toBe(+ flatWorkflowVersion.id,+ );++ return result.manifest.version;+ };++ it('exports a trigger without a universal identifier, and apply writes none', () => {+ const { trigger } = exportBuilderVersion({+ triggers: [recordCreatedTrigger()],+ steps: [createRecordStep()],+ });++ expect(trigger).toEqual({+ type: 'DATABASE_EVENT',+ nextStepIds: [STEP_ID],+ settings: { objectUniversalIdentifier: OBJECT_ID, action: 'created' },+ });++ const reproduced = fromWorkflowManifestToUniversalFlatWorkflowOrThrow({+ manifest: buildWorkflow({ trigger }),+ applicationUniversalIdentifier: APPLICATION_ID,+ now: '2026-10-27T00:00:00.000Z',+ ...references,+ });++ expect(+ reproduced.flatUniversalWorkflowVersion?.triggers?.[0],+ ).not.toHaveProperty('universalIdentifier');+ });++ it.each([+ { name: 'Launch manually', type: 'MANUAL', settings: { outputSchema: {} } },+ {+ name: 'Every day at 06:40 UTC',+ type: 'CRON',+ settings: { type: 'CUSTOM', pattern: '40 6 * * *', outputSchema: {} },+ },+ {+ name: 'Company created',+ type: 'DATABASE_EVENT',+ settings: { eventName: 'ticket.created', outputSchema: {} },+ },+ ])(+ 'exports the builder name "$name" of a $type trigger',+ (builderTrigger) => {+ const { trigger } = exportBuilderVersion({+ triggers: [recordCreatedTrigger(builderTrigger)],+ steps: [createRecordStep()],+ });++ expect(trigger.name).toBe(builderTrigger.name);+ },+ );++ it('exports a moved trigger position, and a missing one as null', () => {+ expect(+ exportBuilderVersion({+ triggers: [recordCreatedTrigger({ position: { x: 120, y: 26 } })],+ steps: [createRecordStep()],+ }).trigger.position,+ ).toEqual({ x: 120, y: 26 });+ expect(+ exportBuilderVersion({+ triggers: [recordCreatedTrigger({ position: undefined })],+ steps: [createRecordStep()],+ }).trigger.position,+ ).toBeNull();+ });++ it('exports the output schema the builder wrote for a POST webhook', () => {+ const outputSchema = {+ message: {+ icon: 'IconVariable',+ isLeaf: true,+ label: 'message',+ type: 'string',+ value: 'Workflow was started',+ },+ };++ const { trigger } = exportBuilderVersion({+ triggers: [+ recordCreatedTrigger({+ name: 'Webhook',+ type: 'WEBHOOK',+ settings: {+ outputSchema,+ httpMethod: 'POST',+ expectedBody: { message: 'Workflow was started' },+ expectedOutputSchema: { message: 'Workflow was started' },+ authentication: null,+ },+ }),+ ],+ steps: [createRecordStep()],+ });++ expect(trigger.outputSchema).toEqual(outputSchema);+ });++ it('exports an empty step output schema the builder kept over the declared one', () => {+ const [step] = exportBuilderVersion({+ triggers: [recordCreatedTrigger()],+ steps: [+ createRecordStep({+ name: 'Enrich the company',+ type: 'LOGIC_FUNCTION',+ settings: {+ outputSchema: {},+ errorHandlingOptions: BUILDER_ERROR_HANDLING_OPTIONS,+ input: {+ logicFunctionId: 'logic-function-id',+ logicFunctionInput: {+ records: ['{{trigger.properties.after.id}}'],+ },+ },+ },+ }),+ ],+ }).steps;++ expect(step.outputSchema).toEqual({});+ });++ it('exports a step without a position as null', () => {+ const [step] = exportBuilderVersion({+ triggers: [recordCreatedTrigger()],+ steps: [createRecordStep({ position: undefined })],+ }).steps;++ expect(step.position).toBeNull();+ });++ it.each([+ { description: 'the valid flag the builder leaves false', overrides: {} },+ { description: 'null next steps', overrides: { nextStepIds: null } },+ {+ description: 'missing next steps',+ overrides: { nextStepIds: undefined },+ },+ {+ description: 'Apollo typenames',+ overrides: {+ __typename: 'WorkflowAction',+ position: { x: 0, y: 180, __typename: 'WorkflowStepPosition' },+ },+ },+ {+ description: 'a retry count stored as a boolean',+ overrides: {+ settings: {+ outputSchema: {},+ errorHandlingOptions: {+ retryOnFailure: { value: false },+ continueOnFailure: { value: false },+ },+ input: { objectName: 'ticket', objectRecord: { name: 'Ticket' } },+ },+ },+ },+ ])('treats $description as the manifest default', ({ overrides }) => {+ expect(+ exportBuilderVersion({+ triggers: [recordCreatedTrigger()],+ steps: [createRecordStep(overrides)],+ }).steps,+ ).toEqual([+ {+ universalIdentifier: STEP_ID,+ name: 'Create Record',+ type: 'CREATE_RECORD',+ nextStepIds: [],+ input: { ...RECORD, objectRecord: { name: 'Ticket' } },+ },+ ]);+ });++ it('ignores the objectType the builder copies from a manual trigger availability', () => {+ const { trigger } = exportBuilderVersion({+ triggers: [+ recordCreatedTrigger({+ name: 'Launch manually',+ type: 'MANUAL',+ settings: {+ objectType: 'ticket',+ availability: {+ type: 'SINGLE_RECORD',+ objectNameSingular: 'ticket',+ },+ outputSchema: {},+ icon: 'IconHandMove',+ isPinned: false,+ },+ }),+ ],+ steps: [createRecordStep()],+ });++ expect(trigger.settings).toEqual({+ availability: {+ type: 'SINGLE_RECORD',+ objectUniversalIdentifier: OBJECT_ID,+ },+ icon: 'IconHandMove',+ isPinned: false,+ });+ });++ it('exports the isFullRecord flag the builder stores on step filters', () => {+ const builderStepFilter = {+ id: 'filter',+ type: 'SELECT',+ value: '["HIGH"]',+ operand: 'IS',+ isFullRecord: false,+ stepOutputKey: '{{trigger.properties.after.priority}}',+ fieldMetadataId: 'priority-field-id',+ stepFilterGroupId: 'group',+ positionInStepFilterGroup: 0,+ };+ const filter = {+ stepFilterGroups: [+ { id: 'group', logicalOperator: 'AND', positionInStepFilterGroup: 0 },+ ],+ stepFilters: [builderStepFilter],+ };++ const { trigger, steps } = exportBuilderVersion({+ triggers: [+ recordCreatedTrigger({+ settings: { eventName: 'ticket.created', outputSchema: {}, filter },+ }),+ ],+ steps: [+ createRecordStep({+ name: 'Filter',+ type: 'FILTER',+ settings: {+ outputSchema: {},+ errorHandlingOptions: BUILDER_ERROR_HANDLING_OPTIONS,+ input: filter,+ },+ }),+ ],+ });+ const { fieldMetadataId: _fieldMetadataId, ...stepFilterWithoutId } =+ builderStepFilter;+ const manifestStepFilter = {+ ...stepFilterWithoutId,+ fieldMetadataUniversalIdentifier: PRIORITY_FIELD_ID,+ };++ expect(trigger.settings).toMatchObject({+ filter: { stepFilters: [manifestStepFilter] },+ });+ expect(steps[0].input).toMatchObject({+ stepFilters: [manifestStepFilter],+ });+ });+});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.tsindex 7eccec47b84..a6ff55edf34 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-flat-workflow-to-workflow-manifest.util.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-flat-workflow-to-workflow-manifest.util.ts@@ -35,13 +35,13 @@ const isReproducedBySyncOrThrow = ({...references,}).flatUniversalWorkflowVersion;- return isSameWorkflowVersionDefinition(- {+ return isSameWorkflowVersionDefinition({+ left: {triggers: reproducedVersion?.triggers ?? null,steps: reproducedVersion?.steps ?? null,},- flatWorkflowVersion,- );+ right: flatWorkflowVersion,+ });};export const fromFlatWorkflowToWorkflowManifest = ({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.tsindex 0c5de3c4d16..31f9a293a32 100644--- 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.ts@@ -5,6 +5,7 @@ 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 { normalizeStoredWorkflowErrorHandlingOptions } from 'src/engine/core-modules/application/application-manifest/utils/normalize-stored-workflow-error-handling-options.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';@@ -264,7 +265,15 @@ export const fromWorkflowActionToWorkflowStepManifest = ({return { reason: unsupportedReason };}- const { outputSchema, errorHandlingOptions } = action.settings;+ const { outputSchema } = action.settings;+ const errorHandlingOptions = isDefined(action.settings.errorHandlingOptions)+ ? normalizeStoredWorkflowErrorHandlingOptions(+ action.settings.errorHandlingOptions,+ )+ : undefined;+ const position = isDefined(action.position)+ ? { x: action.position.x, y: action.position.y }+ : null;const expectedOutputSchema ='expectedOutputSchema' in action.settings? action.settings.expectedOutputSchema@@ -277,10 +286,7 @@ export const fromWorkflowActionToWorkflowStepManifest = ({? { 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 } }- : {}),+ ...(isEqual(position, { x: 0, y: (index + 1) * 180 }) ? {} : { position }),input,} as WorkflowStepManifest;const isDefaultOutputSchema = isEqual(@@ -312,16 +318,7 @@ export const fromWorkflowActionToWorkflowStepManifest = ({...(!isDefined(errorHandlingOptions) ||isEqual(errorHandlingOptions, DEFAULT_ERROR_HANDLING_OPTIONS)? {}- : {- errorHandlingOptions: {- retryOnFailure: {- value: errorHandlingOptions.retryOnFailure.value,- },- continueOnFailure: {- value: errorHandlingOptions.continueOnFailure.value,- },- },- }),+ : { errorHandlingOptions }),},};};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 8b3d9dc7bbf..d036a9d0e6e 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@@ -98,9 +98,9 @@ export const fromWorkflowManifestToUniversalFlatWorkflowOrThrow = ({const keptActiveVersion =isDefined(activeVersion) &&- isSameWorkflowVersionDefinition(activeVersion, {- triggers: [trigger],- steps,+ isSameWorkflowVersionDefinition({+ left: activeVersion,+ right: { triggers: [trigger], steps },})? activeVersion: undefined;diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.tsindex 2221fac92f9..b34244bc3d7 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts@@ -223,7 +223,9 @@ export const fromWorkflowStepManifestToActionOrThrow = ({type: step.type,valid: true,nextStepIds: step.nextStepIds,- position: step.position ?? { x: 0, y: (index + 1) * 180 },+ ...(step.position === null+ ? {}+ : { position: step.position ?? { x: 0, y: (index + 1) * 180 } }),settings: {input: structuredClone(input),outputSchema: structuredClone(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 dcf4417606c..bf99d8415c3 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,18 +1,22 @@import { msg } from '@lingui/core/macro';import { type WorkflowTriggerManifest } from 'twenty-shared/application';-import { getOutputSchemaFromValue } from 'twenty-shared/logic-function';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 {+ computeWorkflowTriggerManifestDefaults,+ DEFAULT_WORKFLOW_TRIGGER_POSITION,+} from 'src/engine/core-modules/application/application-manifest/utils/compute-workflow-trigger-manifest-defaults.util';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,ApplicationExceptionCode,} from 'src/engine/core-modules/application/application.exception';+import { type OutputSchema } from 'src/modules/workflow/workflow-builder/workflow-schema/types/output-schema.type';import { type UpdateEventTriggerSettings } from 'src/modules/workflow/workflow-trigger/automated-trigger/constants/automated-trigger-settings';import {type WorkflowCronTrigger,@@ -47,14 +51,29 @@ type WebhookTriggerManifest = Extract<{ type: 'WEBHOOK' }>;-const DATABASE_EVENT_TRIGGER_NAME_BY_ACTION: Record<- DatabaseEventTriggerManifest['settings']['action'],- string-> = {- created: 'Record is created',- updated: 'Record is updated',- deleted: 'Record is deleted',- upserted: 'Record is created or updated',+type TriggerBase = Pick<+ WorkflowTrigger,+ 'name' | 'nextStepIds' | 'position'+> & { universalIdentifier?: string };++const fromTriggerManifestBase = (+ trigger: WorkflowTriggerManifest,+): { base: TriggerBase; outputSchema: OutputSchema } => {+ const defaults = computeWorkflowTriggerManifestDefaults(trigger);+ const { universalIdentifier, name, nextStepIds, position } = trigger;++ return {+ base: {+ ...(isDefined(universalIdentifier) ? { universalIdentifier } : {}),+ name: name ?? defaults.name,+ nextStepIds,+ ...(position === null+ ? {}+ : { position: position ?? DEFAULT_WORKFLOW_TRIGGER_POSITION }),+ },+ outputSchema: (trigger.outputSchema ??+ defaults.outputSchema) as OutputSchema,+ };};const fromManualTriggerManifestOrThrow = ({@@ -64,18 +83,17 @@ const fromManualTriggerManifestOrThrow = ({trigger: ManualTriggerManifest;resolvers: WorkflowManifestReferenceResolvers;}): WorkflowManualTrigger => {- const { settings, ...identity } = trigger;+ const { settings } = trigger;+ const { base, outputSchema } = fromTriggerManifestBase(trigger);const availability = settings?.availability;const icon = settings?.icon;const isPinned = settings?.isPinned;return {- ...identity,- name: 'Manual trigger',+ ...base,type: WorkflowTriggerType.MANUAL,- position: { x: 0, y: 0 },settings: {- outputSchema: {},+ outputSchema,...(isDefined(icon) ? { icon } : {}),...(isDefined(isPinned) ? { isPinned } : {}),...(isDefined(availability)@@ -98,13 +116,11 @@ const fromManualTriggerManifestOrThrow = ({const fromCronTriggerManifestOrThrow = (trigger: CronTriggerManifest,): WorkflowCronTrigger => {- const { settings, ...identity } = trigger;+ const { base, outputSchema } = fromTriggerManifestBase(trigger);const cronTrigger = {- ...identity,- name: 'On a schedule',+ ...base,type: WorkflowTriggerType.CRON,- position: { x: 0, y: 0 },- settings: { ...settings, outputSchema: {} },+ settings: { ...trigger.settings, outputSchema },} satisfies WorkflowCronTrigger;try {@@ -147,7 +163,8 @@ const fromDatabaseEventTriggerManifestOrThrow = ({trigger: DatabaseEventTriggerManifest;resolvers: WorkflowManifestReferenceResolvers;}): WorkflowDatabaseEventTrigger => {- const { settings, ...identity } = trigger;+ const { settings } = trigger;+ const { base, outputSchema } = fromTriggerManifestBase(trigger);const databaseEventSettings: WorkflowDatabaseEventTrigger['settings'] &Partial<UpdateEventTriggerSettings> = {@@ -155,7 +172,7 @@ const fromDatabaseEventTriggerManifestOrThrow = ({resolvers.objectName(settings.objectUniversalIdentifier),settings.action,),- outputSchema: {},+ outputSchema,...(isNonEmptyArray(settings.fieldUniversalIdentifiers)? {fields: settings.fieldUniversalIdentifiers.map(@@ -185,19 +202,21 @@ const fromDatabaseEventTriggerManifestOrThrow = ({};return {- ...identity,- name: DATABASE_EVENT_TRIGGER_NAME_BY_ACTION[settings.action],+ ...base,type: WorkflowTriggerType.DATABASE_EVENT,- position: { x: 0, y: 0 },settings: databaseEventSettings,} satisfies WorkflowDatabaseEventTrigger;};-const fromWebhookTriggerManifestSettings = (- settings: WebhookTriggerManifest['settings'],-): WorkflowWebhookTrigger['settings'] => {+const fromWebhookTriggerManifestSettings = ({+ settings,+ outputSchema,+}: {+ settings: WebhookTriggerManifest['settings'];+ outputSchema: OutputSchema;+}): WorkflowWebhookTrigger['settings'] => {if (settings.httpMethod === 'GET') {- return { httpMethod: 'GET', authentication: null, outputSchema: {} };+ return { httpMethod: 'GET', authentication: null, outputSchema };}return {@@ -205,21 +224,20 @@ const fromWebhookTriggerManifestSettings = (authentication: null,expectedBody: settings.expectedBody,expectedOutputSchema: settings.expectedBody,- outputSchema: getOutputSchemaFromValue(settings.expectedBody),+ outputSchema,};};const fromWebhookTriggerManifest = (trigger: WebhookTriggerManifest,): WorkflowWebhookTrigger => {- const { settings, ...identity } = trigger;+ const { settings } = trigger;+ const { base, outputSchema } = fromTriggerManifestBase(trigger);return {- ...identity,- name: 'Webhook',+ ...base,type: WorkflowTriggerType.WEBHOOK,- position: { x: 0, y: 0 },- settings: fromWebhookTriggerManifestSettings(settings),+ settings: fromWebhookTriggerManifestSettings({ settings, outputSchema }),} satisfies WorkflowWebhookTrigger;};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.tsindex aede6269242..52ae1231389 100644--- 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.ts@@ -1,11 +1,17 @@import { type WorkflowTriggerManifest } from 'twenty-shared/application';+import isEqual from 'lodash.isequal';import {isDefined,isNonEmptyArray,+ isPlainObject,sortKeysDeeply,} from 'twenty-shared/utils';import { type WorkflowManifestReferences } from 'src/engine/core-modules/application/application-manifest/types/workflow-manifest-references.type';+import {+ computeWorkflowTriggerManifestDefaults,+ DEFAULT_WORKFLOW_TRIGGER_POSITION,+} from 'src/engine/core-modules/application/application-manifest/utils/compute-workflow-trigger-manifest-defaults.util';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 {@@ -180,10 +186,6 @@ export const fromWorkflowTriggerToWorkflowTriggerManifest = ({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();@@ -192,12 +194,33 @@ export const fromWorkflowTriggerToWorkflowTriggerManifest = ({return { reason: unsupportedReason };}+ const manifestWithoutBuilderState = {+ ...(isDefined(trigger.universalIdentifier)+ ? { universalIdentifier: trigger.universalIdentifier }+ : {}),+ type: trigger.type,+ nextStepIds: trigger.nextStepIds ?? [],+ ...(isDefined(settings) ? { settings: sortKeysDeeply(settings) } : {}),+ } as WorkflowTriggerManifest;+ const defaults = computeWorkflowTriggerManifestDefaults(+ manifestWithoutBuilderState,+ );+ const { outputSchema } = trigger.settings;+ const position = isDefined(trigger.position)+ ? { x: trigger.position.x, y: trigger.position.y }+ : null;+return {manifest: {- universalIdentifier: trigger.universalIdentifier,- type: trigger.type,- nextStepIds: trigger.nextStepIds ?? [],- ...(isDefined(settings) ? { settings: sortKeysDeeply(settings) } : {}),- } as WorkflowTriggerManifest,+ ...manifestWithoutBuilderState,+ ...(trigger.name !== defaults.name ? { name: trigger.name } : {}),+ ...(isEqual(position, DEFAULT_WORKFLOW_TRIGGER_POSITION)+ ? {}+ : { position }),+ ...(isPlainObject(outputSchema) &&+ !isEqual(outputSchema, defaults.outputSchema)+ ? { outputSchema: sortKeysDeeply(outputSchema) }+ : {}),+ },};};diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/types/stored-workflow-version-definition.type.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/types/stored-workflow-version-definition.type.tsnew file mode 100644index 00000000000..005103d938c--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/types/stored-workflow-version-definition.type.ts@@ -0,0 +1,23 @@+// Version jsonb as builders of every age wrote it, wider than the typed trigger and step definitions+export type StoredWorkflowErrorHandlingOptions = {+ retryOnFailure: { value: number | boolean };+ continueOnFailure: { value: boolean };+};++export type StoredWorkflowNodeSettings = {+ objectType?: string;+ errorHandlingOptions?: StoredWorkflowErrorHandlingOptions;+} & Record<string, unknown>;++export type StoredWorkflowNode = {+ type: string;+ valid?: boolean;+ position?: ({ x: number; y: number } & Record<string, unknown>) | null;+ nextStepIds?: string[] | null;+ settings?: StoredWorkflowNodeSettings;+} & Record<string, unknown>;++export type StoredWorkflowVersionDefinition = {+ triggers?: StoredWorkflowNode[] | null;+ steps?: StoredWorkflowNode[] | null;+};diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/compute-workflow-manifest-output-schema.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/compute-workflow-manifest-output-schema.util.spec.tsindex b50c4c12437..5e22e43e90b 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/compute-workflow-manifest-output-schema.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/compute-workflow-manifest-output-schema.util.spec.ts@@ -61,3 +61,14 @@ describe('computeWorkflowManifestOutputSchema', () => {expect(outputSchema).toBe(AGENT_OUTPUT_SCHEMA);});});++describe('computeWorkflowManifestOutputSchema with a stated output schema', () => {+ it('keeps an empty output schema the workflow builder stored', () => {+ expect(+ computeWorkflowManifestOutputSchema({+ step: { ...buildAiAgentStep({}), outputSchema: {} },+ references,+ }),+ ).toEqual({});+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/is-same-workflow-version-definition.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/is-same-workflow-version-definition.util.spec.tsnew file mode 100644index 00000000000..2088e72e3c2--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/is-same-workflow-version-definition.util.spec.ts@@ -0,0 +1,124 @@+import {+ type StoredWorkflowNode,+ type StoredWorkflowVersionDefinition,+} from 'src/engine/core-modules/application/application-manifest/types/stored-workflow-version-definition.type';+import { isSameWorkflowVersionDefinition } from 'src/engine/core-modules/application/application-manifest/utils/is-same-workflow-version-definition.util';++const STEP_ID = '40000000-0000-4000-8000-000000000000';++const buildDefinition = ({+ trigger = {},+ step = {},+}: {+ trigger?: Partial<StoredWorkflowNode>;+ step?: Partial<StoredWorkflowNode>;+}): StoredWorkflowVersionDefinition => ({+ triggers: [+ {+ name: 'Launch manually',+ type: 'MANUAL',+ position: { x: 0, y: 0 },+ nextStepIds: [STEP_ID],+ settings: { outputSchema: {}, availability: { type: 'GLOBAL' } },+ ...trigger,+ },+ ],+ steps: [+ {+ id: STEP_ID,+ name: 'Create Record',+ type: 'CREATE_RECORD',+ valid: true,+ position: { x: 0, y: 180 },+ nextStepIds: [],+ settings: {+ outputSchema: {},+ errorHandlingOptions: {+ retryOnFailure: { value: 0 },+ continueOnFailure: { value: false },+ },+ input: { objectName: 'ticket', objectRecord: {} },+ },+ ...step,+ },+ ],+});++describe('isSameWorkflowVersionDefinition', () => {+ it.each([+ { description: 'the step valid flag', step: { valid: false } },+ { description: 'null next steps', step: { nextStepIds: null } },+ { description: 'missing next steps', step: { nextStepIds: undefined } },+ {+ description: 'Apollo typenames',+ step: {+ __typename: 'WorkflowAction',+ position: { x: 0, y: 180, __typename: 'WorkflowStepPosition' },+ },+ },+ {+ description: 'a retry count stored as a boolean',+ step: {+ settings: {+ outputSchema: {},+ errorHandlingOptions: {+ retryOnFailure: { value: false },+ continueOnFailure: { value: false },+ },+ input: { objectName: 'ticket', objectRecord: {} },+ },+ },+ },+ {+ description: 'the objectType of a manual trigger',+ trigger: {+ settings: {+ outputSchema: {},+ availability: { type: 'GLOBAL' },+ objectType: 'ticket',+ },+ },+ },+ ])('ignores $description, which no run reads', ({ trigger, step }) => {+ expect(+ isSameWorkflowVersionDefinition({+ left: buildDefinition({}),+ right: buildDefinition({ trigger, step }),+ }),+ ).toBe(true);+ });++ it('treats a null position as a missing one', () => {+ expect(+ isSameWorkflowVersionDefinition({+ left: buildDefinition({ step: { position: null } }),+ right: buildDefinition({ step: { position: undefined } }),+ }),+ ).toBe(true);+ });++ it.each([+ { description: 'a moved step', step: { position: { x: 10, y: 180 } } },+ { description: 'a renamed trigger', trigger: { name: 'Run it' } },+ {+ description: 'a step retried twice',+ step: {+ settings: {+ outputSchema: {},+ errorHandlingOptions: {+ retryOnFailure: { value: 2 },+ continueOnFailure: { value: false },+ },+ input: { objectName: 'ticket', objectRecord: {} },+ },+ },+ },+ ])('tells apart $description', ({ trigger, step }) => {+ expect(+ isSameWorkflowVersionDefinition({+ left: buildDefinition({}),+ right: buildDefinition({ trigger, step }),+ }),+ ).toBe(false);+ });+});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.tsindex 354c52b056f..97383318d90 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-workflows-manifest.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-workflows-manifest.util.spec.ts@@ -498,19 +498,17 @@ describe('reconstructWorkflowsManifest', () => {universalIdentifier: 'e1000000-0000-4000-8000-000000000000',versionOverrides: { status: WorkflowVersionStatus.DEACTIVATED },});- const renamedTrigger = builderWorkflow({+ const unreproducible = builderWorkflow({universalIdentifier: 'e2000000-0000-4000-8000-000000000000',});- const [trigger] = renamedTrigger.flatWorkflowVersion.triggers ?? [];- renamedTrigger.flatWorkflowVersion = {- ...renamedTrigger.flatWorkflowVersion,- triggers: [{ ...trigger, name: 'Launch manually' }],- };+ Object.assign(unreproducible.flatWorkflowVersion.triggers?.[0] ?? {}, {+ propertyNoManifestFieldHolds: true,+ });expect(reconstruct({- synced: [deactivated, renamedTrigger],+ synced: [deactivated, unreproducible],isWorkspaceCustomApplication: true,}),).toEqual({diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-manifest-output-schema.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-manifest-output-schema.util.tsindex 0078e964a6a..df9299a9a3c 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-manifest-output-schema.util.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-manifest-output-schema.util.ts@@ -16,10 +16,7 @@ export const computeWorkflowManifestOutputSchema = ({| 'agentOutputSchemaByUniversalIdentifier'>;}): Record<string, unknown> => {- if (- isDefined(step.outputSchema) &&- Object.keys(step.outputSchema).length > 0- ) {+ if (isDefined(step.outputSchema)) {return step.outputSchema;}diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-trigger-manifest-defaults.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-trigger-manifest-defaults.util.tsnew file mode 100644index 00000000000..2e1ab8e1116--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/compute-workflow-trigger-manifest-defaults.util.ts@@ -0,0 +1,36 @@+import { type WorkflowTriggerManifest } from 'twenty-shared/application';+import { getOutputSchemaFromValue } from 'twenty-shared/logic-function';+import { WORKFLOW_TRIGGER_DEFAULT_NAMES } from 'twenty-shared/workflow';++import { assertNever } from 'src/utils/assert';++export const DEFAULT_WORKFLOW_TRIGGER_POSITION = { x: 0, y: 0 };++export const computeWorkflowTriggerManifestDefaults = (+ trigger: WorkflowTriggerManifest,+): { name: string; outputSchema: Record<string, unknown> } => {+ switch (trigger.type) {+ case 'MANUAL':+ // Not the builder's 'Launch manually', which would rename the manual trigger of every synced app+ return { name: 'Manual trigger', outputSchema: {} };+ case 'CRON':+ return { name: WORKFLOW_TRIGGER_DEFAULT_NAMES.CRON, outputSchema: {} };+ case 'DATABASE_EVENT':+ return {+ name: WORKFLOW_TRIGGER_DEFAULT_NAMES.DATABASE_EVENT[+ trigger.settings.action+ ],+ outputSchema: {},+ };+ case 'WEBHOOK':+ return {+ name: WORKFLOW_TRIGGER_DEFAULT_NAMES.WEBHOOK,+ outputSchema:+ trigger.settings.httpMethod === 'POST'+ ? getOutputSchemaFromValue(trigger.settings.expectedBody)+ : {},+ };+ default:+ return assertNever(trigger);+ }+};diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/is-same-workflow-version-definition.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/is-same-workflow-version-definition.util.tsindex 969937d41af..5640fe5a476 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/is-same-workflow-version-definition.util.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/is-same-workflow-version-definition.util.ts@@ -1,19 +1,68 @@import isEqual from 'lodash.isequal';+import { isDefined } from 'twenty-shared/utils';-import { type UniversalFlatWorkflowVersion } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-workflow-version.type';+import {+ type StoredWorkflowNode,+ type StoredWorkflowNodeSettings,+ type StoredWorkflowVersionDefinition,+} from 'src/engine/core-modules/application/application-manifest/types/stored-workflow-version-definition.type';+import { normalizeStoredWorkflowErrorHandlingOptions } from 'src/engine/core-modules/application/application-manifest/utils/normalize-stored-workflow-error-handling-options.util';-type WorkflowVersionDefinition = Pick<- UniversalFlatWorkflowVersion,- 'triggers' | 'steps'->;+// Only state no run reads is normalized, so a manifest edit is never compared away+const normalizeSettings = ({+ type,+ settings: { objectType, errorHandlingOptions, ...rest },+}: {+ type: string;+ settings: StoredWorkflowNodeSettings;+}) => ({+ ...rest,+ ...(type === 'MANUAL' ? {} : { objectType }),+ ...(isDefined(errorHandlingOptions)+ ? {+ errorHandlingOptions:+ normalizeStoredWorkflowErrorHandlingOptions(errorHandlingOptions),+ }+ : {}),+});++const normalizeNode = ({+ valid: _valid,+ position,+ nextStepIds,+ settings,+ ...rest+}: StoredWorkflowNode) => ({+ ...rest,+ nextStepIds: nextStepIds ?? [],+ ...(isDefined(position) ? { position } : {}),+ ...(isDefined(settings)+ ? { settings: normalizeSettings({ type: rest.type, settings }) }+ : {}),+});// Compared as stored in jsonb, where undefined properties are dropped-const toJsonValue = ({ triggers, steps }: WorkflowVersionDefinition): unknown =>- JSON.parse(+const toJsonValue = ({+ triggers,+ steps,+}: StoredWorkflowVersionDefinition): unknown => {+ const stored: StoredWorkflowVersionDefinition = JSON.parse(JSON.stringify({ triggers: triggers ?? null, steps: steps ?? null }),+ (key, value) => (key === '__typename' ? undefined : value),+ );++ return JSON.parse(+ JSON.stringify({+ triggers: stored.triggers?.map(normalizeNode) ?? null,+ steps: stored.steps?.map(normalizeNode) ?? null,+ }),);+};-export const isSameWorkflowVersionDefinition = (- left: WorkflowVersionDefinition,- right: WorkflowVersionDefinition,-): boolean => isEqual(toJsonValue(left), toJsonValue(right));+export const isSameWorkflowVersionDefinition = ({+ left,+ right,+}: {+ left: StoredWorkflowVersionDefinition;+ right: StoredWorkflowVersionDefinition;+}): boolean => isEqual(toJsonValue(left), toJsonValue(right));diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/normalize-stored-workflow-error-handling-options.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/normalize-stored-workflow-error-handling-options.util.tsnew file mode 100644index 00000000000..d737049be30--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/normalize-stored-workflow-error-handling-options.util.ts@@ -0,0 +1,10 @@+import { type StoredWorkflowErrorHandlingOptions } from 'src/engine/core-modules/application/application-manifest/types/stored-workflow-version-definition.type';++// Older builders stored the retry count as a boolean, which runs read as Number(value)+export const normalizeStoredWorkflowErrorHandlingOptions = ({+ retryOnFailure,+ continueOnFailure,+}: StoredWorkflowErrorHandlingOptions) => ({+ retryOnFailure: { value: Number(retryOnFailure.value) },+ continueOnFailure: { value: continueOnFailure.value },+});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 36d713be2c7..be776d17560 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@@ -88,7 +88,6 @@ import { isDefined } from 'twenty-shared/utils';import { version as getUuidVersion, v4 } from 'uuid';import { type ApplicationManifestMigrationService } from 'src/engine/core-modules/application/application-manifest/application-manifest-migration.service';-import { fromWorkflowManifestToUniversalFlatWorkflowOrThrow } from 'src/engine/core-modules/application/application-manifest/converters/from-workflow-manifest-to-universal-flat-workflow-or-throw.util';import { type ApplicationService } from 'src/engine/core-modules/application/application.service';import { WORKSPACE_CUSTOM_APPLICATION_NAME } from 'src/engine/core-modules/application/constants/workspace-custom-application.constant';import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';@@ -1988,23 +1987,31 @@ describe('Application export - workflows built in the workflow builder', () => {let workflowUniversalIdentifier: string;let workflowRunId: string | undefined;+ let stepId: string;+const buildManifest = (url: string): WorkflowManifest => ({universalIdentifier: workflowUniversalIdentifier,name: workflowName,version: {trigger: {- universalIdentifier: workflowNodeIdentifier(40),+ name: 'Launch manually',type: 'MANUAL',- nextStepIds: [workflowNodeIdentifier(41)],- settings: { availability: { type: 'GLOBAL' }, isPinned: true },+ nextStepIds: [stepId],+ settings: {+ availability: { type: 'GLOBAL' },+ icon: 'IconHandMove',+ isPinned: false,+ },},steps: [{- universalIdentifier: workflowNodeIdentifier(41),- name: 'Notify sales',+ universalIdentifier: stepId,+ name: 'HTTP Request',type: 'HTTP_REQUEST',nextStepIds: [],- input: { method: 'POST', url },+ position: { x: 200, y: 0 },+ input: { method: 'POST', url, headers: {}, body: {} },+ expectedOutputSchema: {},},],},@@ -2036,7 +2043,6 @@ describe('Application export - workflows built in the workflow builder', () => {};beforeAll(async () => {- const customFlatApplication = await findWorkspaceCustomFlatApplication();const createdWorkflow = await createCoreWorkflow({ name: workflowName });coreWorkflowId = createdWorkflow.coreWorkflowId;@@ -2049,38 +2055,56 @@ describe('Application export - workflows built in the workflow builder', () => {workflowUniversalIdentifier = universalIdentifier;- // The builder stores whatever trigger and steps it is sent, so it is sent exactly what a manifest produces- const { triggers, steps } =- fromWorkflowManifestToUniversalFlatWorkflowOrThrow({- manifest: buildManifest('http://localhost:1/before'),- applicationUniversalIdentifier:- customFlatApplication.universalIdentifier,- now: new Date().toISOString(),- logicFunctionIdByUniversalIdentifier: new Map(),- }).flatUniversalWorkflowVersion!;- const [trigger] = triggers!;- const [step] = steps!;-+ // Same calls and payloads as the builder front, so the stored version is a real builder oneawait updateCoreWorkflowVersionTrigger({coreWorkflowVersionId: builderVersionId,- trigger: { ...trigger, nextStepIds: [] },+ trigger: {+ name: 'Launch manually',+ type: 'MANUAL',+ position: { x: 0, y: 0 },+ settings: {+ availability: { type: 'GLOBAL' },+ outputSchema: {},+ icon: 'IconHandMove',+ isPinned: false,+ },+ },});- await createCoreWorkflowVersionStep({++ const createdStep = await createCoreWorkflowVersionStep({coreWorkflowVersionId: builderVersionId,stepType: 'HTTP_REQUEST',- id: step.id,- });- await updateCoreWorkflowVersionTrigger({- coreWorkflowVersionId: builderVersionId,- trigger,});++ stepId = createdStep.id;+await updateCoreWorkflowVersionStep({coreWorkflowVersionId: builderVersionId,- step,+ step: {+ ...createdStep,+ settings: {+ ...createdStep.settings,+ input: {+ ...createdStep.settings.input,+ method: 'POST',+ url: 'http://localhost:1/before',+ },+ },+ },});await activateCoreWorkflowVersion({coreWorkflowVersionId: builderVersionId,});++ const { triggers, steps } = (+ await global.testDataSource.query(+ `SELECT triggers, steps FROM core."workflowVersion" WHERE id = $1`,+ [builderVersionId],+ )+ )[0];++ expect(triggers[0]).not.toHaveProperty('universalIdentifier');+ expect(steps[0]).toMatchObject({ valid: false });}, 60000);afterAll(async () => {diff --git a/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts b/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.tsindex 96c861def47..e3e1867f86b 100644--- a/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts+++ b/packages/twenty-shared/src/application/__tests__/workflowManifestType.spec.ts@@ -480,6 +480,7 @@ describe('workflow manifest database event trigger', () => {value: 'open',stepFilterGroupId: 'group',fieldMetadataUniversalIdentifier: FIELD_ID,+ isFullRecord: false,},],},@@ -592,6 +593,54 @@ describe('workflow manifest database event trigger', () => {});});+describe('workflow manifest state stored by the workflow builder', () => {+ const { universalIdentifier: _universalIdentifier, ...triggerWithoutId } =+ workflow.version.trigger;++ const withTrigger = (trigger: Record<string, unknown>) => ({+ ...workflow,+ version: { ...workflow.version, trigger },+ });++ it('accepts a trigger without a universal identifier, with its name, position and output schema', () => {+ expect(+ workflowManifestSchema.safeParse(+ withTrigger({+ ...triggerWithoutId,+ name: 'Launch manually',+ position: { x: 120, y: 26 },+ outputSchema: {},+ }),+ ).success,+ ).toBe(true);+ });++ it('accepts a null position for a trigger or step the builder placed nowhere', () => {+ const [firstStep, ...otherSteps] = workflow.version.steps;++ expect(+ workflowManifestSchema.safeParse({+ ...workflow,+ version: {+ trigger: { ...workflow.version.trigger, position: null },+ steps: [{ ...firstStep, position: null }, ...otherSteps],+ },+ }).success,+ ).toBe(true);+ });++ it.each([+ { problem: 'an empty name', trigger: { name: '' } },+ { problem: 'a position without coordinates', trigger: { position: {} } },+ ])('rejects $problem', ({ trigger }) => {+ expect(+ workflowManifestSchema.safeParse(+ withTrigger({ ...workflow.version.trigger, ...trigger }),+ ).success,+ ).toBe(false);+ });+});+describe('workflow manifest isSystem', () => {it('accepts a workflow flagged as system', () => {expect(diff --git a/packages/twenty-shared/src/application/index.ts b/packages/twenty-shared/src/application/index.tsindex 5691ef1afb5..a69f12d9f18 100644--- a/packages/twenty-shared/src/application/index.ts+++ b/packages/twenty-shared/src/application/index.ts@@ -314,6 +314,7 @@ export type { WorkflowManifest } from './workflowManifestType';export { workflowManifestSchema } from './workflowManifestType';export type { WorkflowStepManifest } from './workflowStepManifestType';export {+ workflowManifestPositionSchema,workflowStepFilterManifestSchema,workflowStepManifestSchema,} from './workflowStepManifestType';diff --git a/packages/twenty-shared/src/application/workflowManifestType.ts b/packages/twenty-shared/src/application/workflowManifestType.tsindex 949b6d43812..1a7aa6df9ba 100644--- a/packages/twenty-shared/src/application/workflowManifestType.ts+++ b/packages/twenty-shared/src/application/workflowManifestType.ts@@ -1,5 +1,7 @@import { z } from 'zod';+import { isDefined } from '@/utils/validation/isDefined';+import { validateWorkflowVariableReferences } from '@/workflow/validation/utils/validate-workflow-variable-references.util';import { workflowStepManifestSchema } from '@/application/workflowStepManifestType';@@ -24,7 +26,7 @@ export const workflowManifestSchema = zworkflow.universalIdentifier,trigger.universalIdentifier,...steps.map((step) => step.universalIdentifier),- ];+ ].filter(isDefined);if (new Set(identities).size !== identities.length) {context.addIssue({diff --git a/packages/twenty-shared/src/application/workflowStepManifestType.ts b/packages/twenty-shared/src/application/workflowStepManifestType.tsindex 80a0a1327ac..bef3d5b8bf9 100644--- a/packages/twenty-shared/src/application/workflowStepManifestType.ts+++ b/packages/twenty-shared/src/application/workflowStepManifestType.ts@@ -26,11 +26,16 @@ import { recordFilterSchema } from '@/workflow/schemas/record-filter-schema';import { stepFilterSchema } from '@/workflow/schemas/step-filter-schema';import { workflowPickRecordStrategySchema } from '@/workflow/schemas/pick-record-action-settings-schema';+export const workflowManifestPositionSchema = z.object({+ x: z.number(),+ y: z.number(),+});+const baseStepShape = {universalIdentifier: z.uuid(),name: z.string().min(1),nextStepIds: z.array(z.uuid()),- position: z.object({ x: z.number(), y: z.number() }).optional(),+ position: workflowManifestPositionSchema.nullable().optional(),outputSchema: z.record(z.string(), z.unknown()).optional(),expectedOutputSchema: z.record(z.string(), z.unknown()).optional(),errorHandlingOptions:diff --git a/packages/twenty-shared/src/application/workflowTriggerManifestType.ts b/packages/twenty-shared/src/application/workflowTriggerManifestType.tsindex 6e673297958..1b9dad40a08 100644--- a/packages/twenty-shared/src/application/workflowTriggerManifestType.ts+++ b/packages/twenty-shared/src/application/workflowTriggerManifestType.ts@@ -1,6 +1,9 @@import { z } from 'zod';-import { workflowStepFilterManifestSchema } from '@/application/workflowStepManifestType';+import {+ workflowManifestPositionSchema,+ workflowStepFilterManifestSchema,+} from '@/application/workflowStepManifestType';import { ViewFilterOperand } from '@/types/ViewFilterOperand';import { isNonEmptyArray } from '@/utils/array/isNonEmptyArray';import { isDefined } from '@/utils/validation/isDefined';@@ -64,11 +67,19 @@ const webhookTriggerSettingsManifestSchema = z.discriminatedUnion(],);+// Optional because the workflow builder stores triggers without one+const baseTriggerShape = {+ universalIdentifier: z.uuid().optional(),+ name: z.string().min(1).optional(),+ nextStepIds: z.array(z.uuid()).min(1),+ position: workflowManifestPositionSchema.nullable().optional(),+ outputSchema: z.record(z.string(), z.unknown()).optional(),+};+const workflowTriggerManifestOptions = [z.strictObject({- universalIdentifier: z.uuid(),+ ...baseTriggerShape,type: z.literal('MANUAL'),- nextStepIds: z.array(z.uuid()).min(1),settings: z.strictObject({availability: manualTriggerAvailabilityManifestSchema.optional(),@@ -91,15 +102,13 @@ const workflowTriggerManifestOptions = [.optional(),}),z.strictObject({- universalIdentifier: z.uuid(),+ ...baseTriggerShape,type: z.literal('CRON'),- nextStepIds: z.array(z.uuid()).min(1),settings: cronTriggerSettingsManifestSchema,}),z.strictObject({- universalIdentifier: z.uuid(),+ ...baseTriggerShape,type: z.literal('DATABASE_EVENT'),- nextStepIds: z.array(z.uuid()).min(1),settings: z.strictObject({objectUniversalIdentifier: z.uuid(),@@ -208,9 +217,8 @@ const workflowTriggerManifestOptions = [}),}),z.strictObject({- universalIdentifier: z.uuid(),+ ...baseTriggerShape,type: z.literal('WEBHOOK'),- nextStepIds: z.array(z.uuid()).min(1),settings: webhookTriggerSettingsManifestSchema,}),] as const;diff --git a/packages/twenty-shared/src/workflow/constants/WorkflowTriggerDefaultNames.ts b/packages/twenty-shared/src/workflow/constants/WorkflowTriggerDefaultNames.tsnew file mode 100644index 00000000000..c38dde7b2da--- /dev/null+++ b/packages/twenty-shared/src/workflow/constants/WorkflowTriggerDefaultNames.ts@@ -0,0 +1,11 @@+// Stored as the trigger name, and the key the builder translates it by+export const WORKFLOW_TRIGGER_DEFAULT_NAMES = {+ CRON: 'On a schedule',+ WEBHOOK: 'Webhook',+ DATABASE_EVENT: {+ created: 'Record is created',+ updated: 'Record is updated',+ deleted: 'Record is deleted',+ upserted: 'Record is created or updated',+ },+} as const;diff --git a/packages/twenty-shared/src/workflow/index.ts b/packages/twenty-shared/src/workflow/index.tsindex c99eda8cc7e..a47926cbd0e 100644--- a/packages/twenty-shared/src/workflow/index.ts+++ b/packages/twenty-shared/src/workflow/index.ts@@ -15,6 +15,7 @@ export { OBJECTS_SYNCED_FROM_CONNECTED_ACCOUNTS } from './constants/ObjectsSynceexport { STEP_RETRY_DELAYS_MS } from './constants/StepRetryDelaysMs';export { TRIGGER_STEP_ID } from './constants/TriggerStepId';export { WORKFLOW_ACTION_FEATURE_FLAGS } from './constants/WorkflowActionFeatureFlags';+export { WORKFLOW_TRIGGER_DEFAULT_NAMES } from './constants/WorkflowTriggerDefaultNames';export { WORKFLOW_TRIGGER_METADATA_KEY } from './constants/WorkflowTriggerMetadataKey';export { WORKFLOW_TRIGGER_METADATA_LABEL } from './constants/WorkflowTriggerMetadataLabel';export { WORKFLOW_TRIGGER_METADATA_WORKSPACE_MEMBER_ID_KEY } from './constants/WorkflowTriggerMetadataWorkspaceMemberIdKey';diff --git a/packages/twenty-shared/src/workflow/schemas/step-filter-schema.ts b/packages/twenty-shared/src/workflow/schemas/step-filter-schema.tsindex f59960777b1..e583969c5fc 100644--- a/packages/twenty-shared/src/workflow/schemas/step-filter-schema.ts+++ b/packages/twenty-shared/src/workflow/schemas/step-filter-schema.ts@@ -12,4 +12,5 @@ export const stepFilterSchema = z.object({positionInStepFilterGroup: z.number().optional(),fieldMetadataId: z.string().optional(),compositeFieldSubFieldName: z.string().optional(),+ isFullRecord: z.boolean().optional(),});