Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

fix(flows): turning on a flow with no trigger now fails cleanly instead of half-publishing it (#16514)

Bartosz Majewski953cbd744b6e
diff --git a/brain/knowledge/flows-execution/flows.md b/brain/knowledge/flows-execution/flows.md
index 8332b72dff6..8059e8570f4 100644
--- a/brain/knowledge/flows-execution/flows.md
+++ b/brain/knowledge/flows-execution/flows.md
@@ -21,6 +21,7 @@ Flows are the core automation primitive: a versioned directed graph of trigger +
### Gotchas
- **Draft edits go through one lock per flow.** `flowService.update` reads the latest version, applies the operation and saves the whole row, so two edits at once (parallel chat tool calls, two tabs, teammates) used to lose all but the last write. The default and note branches now run inside `distributedLock` key `flow-draft-update-<flowId>`. Anything new that writes a draft version should go through `flowService.update` rather than saving the row itself.
- **Publishing has two entry points and only one of them is the obvious one — put any publish-time guard in `setPublishedVersion`.** `updatedPublishedVersionId` is the direct path (`LOCK_AND_PUBLISH`), but the EE approval path publishes from `flow-approval-request.service.ts` by calling `flowService.setPublishedVersion` inside its own transaction, skipping everything the direct path does around it. A validation added to `updatedPublishedVersionId` is therefore silently absent whenever a sensitive project routes through approval — which is the worst case, since a flow can sit pending while the thing it references is deleted. Found on [#14934](https://github.com/activepieces/activepieces/pull/14934), where approving published a flow whose agent had left the project and returned a clean 200. Note the two checks see different data: `applyOperation` recomputes `flowVersion.agentIds` from the steps on lock (`flow-version.service.ts`, `extractAgentIds`), so a pre-lock check reads the stored column while one inside `setPublishedVersion` reads the freshly derived value — a poisoned or stale column only trips the former.
+- **A flow with no trigger selected can be published, but never enabled.** `assertTriggerIsSelected` (EMPTY trigger, or a piece trigger without `triggerName`) runs twice in `flow.service.ts`: in `LOCK_AND_PUBLISH` before `routePublish` when the requested status is ENABLED (followed by `triggerUtils.getPieceTriggerOrThrow`, so a trigger the piece registry cannot resolve is refused there too), and in `applyStatusChange` before the trigger is switched on. The publish check cannot live in `setPublishedVersion`, because by then the approval path has locked the draft at submit time and the direct path has switched off the live trigger. A `{ status: DISABLED }` publish still goes through, since connection replace republishes with the flow's current status and a disabled trigger-less flow must keep working there. ENG-855.
- **Step settings autosave from inside the form resolver, on every validating `setValue`.** `step-settings/index.tsx` runs `applyOperation(UPDATE_ACTION/UPDATE_TRIGGER)` in its `resolver` whenever the new values differ from the last saved snapshot — it is *not* gated on `isDirty` or on a submit. Any transient value a component writes with `shouldValidate: true` is therefore persisted immediately, including one it intends to overwrite a moment later from an async response.
- **A CODE step's compiled size is its `packageJson`, not its code — bundling *inlines* `node_modules`, it does not exclude it.** This gets assumed backwards a lot: there is no `node_modules` at runtime precisely *because* esbuild inlines every dependency into the step's `index.js`. Measured on cloud, Aug 2026: a step with **1,870 characters** of user source and `{"pdfkit":"0.14.0","aws-sdk":"2.1531.0","uuid":"9.0.1"}` compiles to **24.13 MB**, of which 24.13 MB is `node_modules` — **21.16 MB of it `aws-sdk` alone**. v2 of that SDK resolves its ~200 service clients by dynamic `require`, so esbuild cannot tree-shake it and inlines all of them; `@aws-sdk/client-*` (v3) would be a few hundred KB. Fleet-wide there were 13,918 compiled steps totalling 1.4 GB, **61 of them over 10 MB**, and per *flow* the totals reach **190.7 MB across 40 code steps**. That per-flow number is the one that matters operationally, because `flowBundleStore.publish` holds a flow's entire compiled output in memory at once (three copies — see the OOM gotcha on [[workers]]). To find the offenders: esbuild leaves `// node_modules/<pkg>/…` markers in the output, so you can attribute bytes per package by summing the lines between markers.
- **Step output nesting (schema v21+)**: every step output is wrapped as `{ output, error? }`; expressions must use the `['output']` accessor. The v20→v21 migration rewrites existing expressions via `expression-rewriter`.
diff --git a/packages/server/api/src/app/flows/flow/flow.service.ts b/packages/server/api/src/app/flows/flow/flow.service.ts
index 88db16f526e..7f3592178cb 100644
--- a/packages/server/api/src/app/flows/flow/flow.service.ts
+++ b/packages/server/api/src/app/flows/flow/flow.service.ts
@@ -1,6 +1,6 @@
import { ActivepiecesError, apId, Cursor, ErrorCode, FlowId, FlowVersionId, isNil, Metadata, PlatformId, ProjectId, SeekPage, tryCatch, UserId } from '@activepieces/core-utils'
import { apDayjs, apDayjsDuration } from '@activepieces/server-utils'
-import { CreateFlowRequest, Flow, FlowCreator, FlowOperationRequest, FlowOperationStatus, FlowOperationType, flowPieceUtil, FlowStatus, FlowTriggerType, FlowVersion, FlowVersionState, PopulatedFlow, requiredActionsUtil, SharedTemplate, TelemetryEventName, TemplateStatus, TemplateType, TriggerSource, UncategorizedFolderId, UserWithMetaInformation } from '@activepieces/shared'
+import { CreateFlowRequest, Flow, FlowCreator, FlowOperationRequest, FlowOperationStatus, FlowOperationType, flowPieceUtil, FlowStatus, FlowTrigger, FlowTriggerType, FlowVersion, FlowVersionState, PopulatedFlow, requiredActionsUtil, SharedTemplate, TelemetryEventName, TemplateStatus, TemplateType, TriggerSource, UncategorizedFolderId, UserWithMetaInformation } from '@activepieces/shared'
import dayjs from 'dayjs'
import { FastifyBaseLogger } from 'fastify'
import { EntityManager, In, IsNull, Not } from 'typeorm'
@@ -17,6 +17,7 @@ import { systemJobsSchedule } from '../../helper/system-jobs/system-job'
import { telemetry } from '../../helper/telemetry.utils'
import { projectService } from '../../project/project-service'
import { triggerSourceService } from '../../trigger/trigger-source/trigger-source-service'
+import { triggerUtils } from '../../trigger/trigger-source/trigger-utils'
import { flowVersionMigrationService } from '../flow-version/flow-version-migration.service'
import { flowVersionRepo, flowVersionService } from '../flow-version/flow-version.service'
import { flowFolderService } from '../folder/folder.service'
@@ -361,6 +362,10 @@ export const flowService = (log: FastifyBaseLogger) => ({
})
}
const requestedStatus = operation.request.status ?? FlowStatus.ENABLED
+ if (requestedStatus === FlowStatus.ENABLED) {
+ assertTriggerIsSelected({ trigger: flowVersionToPublish.trigger })
+ await triggerUtils(log).getPieceTriggerOrThrow({ flowVersion: flowVersionToPublish, projectId })
+ }
const route = await publishHooksFactory.get(log).routePublish({ flow, projectId, platformId, userId })
if (route === 'NEEDS_APPROVAL') {
await publishHooksFactory.get(log).submitForApproval({
@@ -769,6 +774,16 @@ async function assertRequiredActionsPresent({ projectId, platformId, flowVersion
})
}
+function assertTriggerIsSelected({ trigger }: { trigger: FlowTrigger }): void {
+ if (trigger.type === FlowTriggerType.PIECE && !isNil(trigger.settings.triggerName)) {
+ return
+ }
+ throw new ActivepiecesError({
+ code: ErrorCode.FLOW_OPERATION_INVALID,
+ params: { message: 'Cannot enable a flow without a trigger, select a trigger first' },
+ })
+}
+
const lockFlowVersionIfNotLocked = async ({
flowVersion,
userId,
@@ -837,6 +852,9 @@ async function applyStatusChange(params: {
flowId: flowToUpdate.id,
versionId: publishedFlowVersionId,
})
+ if (params.newStatus === FlowStatus.ENABLED) {
+ assertTriggerIsSelected({ trigger: publishedFlowVersion.trigger })
+ }
await flowSideEffects(log).preUpdateStatus({
flowToUpdate,
diff --git a/packages/server/api/test/integration/ce/flows/flow/flow.test.ts b/packages/server/api/test/integration/ce/flows/flow/flow.test.ts
index 7a461030f08..22b39b0a088 100644
--- a/packages/server/api/test/integration/ce/flows/flow/flow.test.ts
+++ b/packages/server/api/test/integration/ce/flows/flow/flow.test.ts
@@ -1,8 +1,9 @@
-import { ErrorCode } from '@activepieces/core-utils'
+import { apId, ErrorCode } from '@activepieces/core-utils'
import { WebhookRenewStrategy } from '@activepieces/pieces-framework'
import {
FlowOperationType,
FlowStatus,
+ FlowTrigger,
FlowTriggerType,
FlowVersionState,
PackageType,
@@ -301,6 +302,120 @@ describe('Flow API', () => {
expect(responseBody.templateId).toBeNull()
}
})
+
+ it('Refuses to publish a draft whose trigger is empty and records nothing', async () => {
+ const ctx = await createTestContext(app!)
+
+ const mockFlow = createMockFlow({
+ projectId: ctx.project.id,
+ status: FlowStatus.DISABLED,
+ })
+ await db.save('flow', mockFlow)
+
+ const mockFlowVersion = createMockFlowVersion({
+ flowId: mockFlow.id,
+ updatedBy: ctx.user.id,
+ state: FlowVersionState.DRAFT,
+ trigger: emptyTrigger(),
+ })
+ await db.save('flow_version', mockFlowVersion)
+
+ const response = await ctx.post(`/v1/flows/${mockFlow.id}`, {
+ type: FlowOperationType.LOCK_AND_PUBLISH,
+ request: {},
+ })
+
+ expect(response?.statusCode).toBe(StatusCodes.BAD_REQUEST)
+ expect(response?.json().code).toBe(ErrorCode.FLOW_OPERATION_INVALID)
+ const flowRow = await db.findOneByOrFail<{ publishedVersionId: string | null }>('flow', { id: mockFlow.id })
+ expect(flowRow.publishedVersionId).toBeNull()
+ const versionRow = await db.findOneByOrFail<{ state: string }>('flow_version', { id: mockFlowVersion.id })
+ expect(versionRow.state).toBe(FlowVersionState.DRAFT)
+ })
+
+ it('Keeps a live flow on its published version when the new draft has an empty trigger', async () => {
+ const ctx = await createTestContext(app!)
+
+ const mockFlow = createMockFlow({
+ projectId: ctx.project.id,
+ status: FlowStatus.ENABLED,
+ })
+ await db.save('flow', mockFlow)
+
+ const publishedVersion = createMockFlowVersion({
+ flowId: mockFlow.id,
+ updatedBy: ctx.user.id,
+ state: FlowVersionState.LOCKED,
+ created: dayjs().subtract(1, 'hour').toISOString(),
+ })
+ const draftVersion = createMockFlowVersion({
+ flowId: mockFlow.id,
+ updatedBy: ctx.user.id,
+ state: FlowVersionState.DRAFT,
+ created: dayjs().toISOString(),
+ trigger: emptyTrigger(),
+ })
+ await db.save('flow_version', [publishedVersion, draftVersion])
+ await db.update('flow', mockFlow.id, { publishedVersionId: publishedVersion.id })
+ await db.save('trigger_source', {
+ id: apId(),
+ created: new Date().toISOString(),
+ updated: new Date().toISOString(),
+ flowId: mockFlow.id,
+ flowVersionId: publishedVersion.id,
+ projectId: ctx.project.id,
+ pieceName: '@activepieces/piece-schedule',
+ pieceVersion: '0.1.5',
+ triggerName: 'every_hour',
+ type: TriggerStrategy.POLLING,
+ simulate: false,
+ schedule: null,
+ deleted: null,
+ })
+
+ const response = await ctx.post(`/v1/flows/${mockFlow.id}`, {
+ type: FlowOperationType.LOCK_AND_PUBLISH,
+ request: {},
+ })
+
+ expect(response?.statusCode).toBe(StatusCodes.BAD_REQUEST)
+ const flowRow = await db.findOneByOrFail<{ status: string, publishedVersionId: string | null }>('flow', { id: mockFlow.id })
+ expect(flowRow.status).toBe(FlowStatus.ENABLED)
+ expect(flowRow.publishedVersionId).toBe(publishedVersion.id)
+ const draftRow = await db.findOneByOrFail<{ state: string }>('flow_version', { id: draftVersion.id })
+ expect(draftRow.state).toBe(FlowVersionState.DRAFT)
+ const triggerSourceRow = await db.findOneBy<{ id: string }>('trigger_source', { flowId: mockFlow.id })
+ expect(triggerSourceRow).not.toBeNull()
+ })
+
+ it('Refuses to enable a flow whose published version has an empty trigger', async () => {
+ const ctx = await createTestContext(app!)
+
+ const mockFlow = createMockFlow({
+ projectId: ctx.project.id,
+ status: FlowStatus.DISABLED,
+ })
+ await db.save('flow', mockFlow)
+
+ const publishedVersion = createMockFlowVersion({
+ flowId: mockFlow.id,
+ updatedBy: ctx.user.id,
+ state: FlowVersionState.LOCKED,
+ trigger: emptyTrigger(),
+ })
+ await db.save('flow_version', publishedVersion)
+ await db.update('flow', mockFlow.id, { publishedVersionId: publishedVersion.id })
+
+ const response = await ctx.post(`/v1/flows/${mockFlow.id}`, {
+ type: FlowOperationType.CHANGE_STATUS,
+ request: { status: FlowStatus.ENABLED },
+ })
+
+ expect(response?.statusCode).toBe(StatusCodes.BAD_REQUEST)
+ expect(response?.json().code).toBe(ErrorCode.FLOW_OPERATION_INVALID)
+ const flowRow = await db.findOneByOrFail<{ status: string }>('flow', { id: mockFlow.id })
+ expect(flowRow.status).toBe(FlowStatus.DISABLED)
+ })
})
describe('List Flows endpoint', () => {
@@ -610,3 +725,14 @@ async function seedFlowsNamed({ projectId, displayNames }: { projectId: string,
displayName: displayNames[index],
})))
}
+
+function emptyTrigger(): FlowTrigger {
+ return {
+ type: FlowTriggerType.EMPTY,
+ name: 'trigger',
+ settings: {},
+ valid: false,
+ displayName: 'Select Trigger',
+ lastUpdatedDate: dayjs().toISOString(),
+ }
+}
diff --git a/packages/server/api/test/integration/ee/agent/agent-controller.test.ts b/packages/server/api/test/integration/ee/agent/agent-controller.test.ts
index df5239bdf8b..4f381e80f06 100644
--- a/packages/server/api/test/integration/ee/agent/agent-controller.test.ts
+++ b/packages/server/api/test/integration/ee/agent/agent-controller.test.ts
@@ -930,7 +930,7 @@ describe('moving an agent to another project', () => {
const published = await ctx.post(`/v1/flows/${flow.id}`, {
type: 'LOCK_AND_PUBLISH',
- request: {},
+ request: { status: FlowStatus.DISABLED },
})
expect(published.statusCode).toBe(StatusCodes.CONFLICT)
diff --git a/packages/server/api/test/integration/ee/flow-approval/flow-approval.test.ts b/packages/server/api/test/integration/ee/flow-approval/flow-approval.test.ts
index 6700315ec21..80a3fd7fb72 100644
--- a/packages/server/api/test/integration/ee/flow-approval/flow-approval.test.ts
+++ b/packages/server/api/test/integration/ee/flow-approval/flow-approval.test.ts
@@ -4,6 +4,7 @@ import {
Flow,
FlowApprovalRequest,
FlowApprovalRequestState,
+ FlowOperationType,
FlowStatus,
FlowVersion,
FlowVersionState,
@@ -144,6 +145,26 @@ describe('flow-approval — routing', () => {
})
})
+describe('flow-approval — submit through publish', () => {
+ it('refuses a draft with an empty trigger before it is locked or submitted', async () => {
+ const ctx = await setupSensitiveCtx()
+ const memberCtx = await createMemberContext(app!, ctx, {
+ projectRole: DefaultProjectRole.EDITOR,
+ })
+ const { flow, version } = await createDraftFlow(ctx)
+
+ const response = await memberCtx.post(`/v1/flows/${flow.id}`, {
+ type: FlowOperationType.LOCK_AND_PUBLISH,
+ request: {},
+ })
+
+ expect(response.statusCode).toBe(StatusCodes.BAD_REQUEST)
+ expect(await db.findOneBy('flow_approval_request', { flowId: flow.id })).toBeNull()
+ const versionRow = await db.findOneByOrFail<{ state: string }>('flow_version', { id: version.id })
+ expect(versionRow.state).toBe(FlowVersionState.DRAFT)
+ })
+})
+
describe('flow-approval — submitForApproval race', () => {
it('two concurrent submits produce exactly one PENDING row', async () => {
const ctx = await setupSensitiveCtx()