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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
fix(flows): edits made at the same time are no longer lost (#16518)
Hazem Adelfa27cca1314e
diff --git a/brain/knowledge/flows-execution/flows.md b/brain/knowledge/flows-execution/flows.mdindex c89dec66180..8332b72dff6 100644--- a/brain/knowledge/flows-execution/flows.md+++ b/brain/knowledge/flows-execution/flows.md@@ -19,6 +19,7 @@ Flows are the core automation primitive: a versioned directed graph of trigger +- Sample data is captured per step (input+output) as File entities per flow version.### 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.- **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.diff --git a/packages/server/api/src/app/flows/flow/flow.service.ts b/packages/server/api/src/app/flows/flow/flow.service.tsindex 1e93741af96..ea09af205f7 100644--- a/packages/server/api/src/app/flows/flow/flow.service.ts+++ b/packages/server/api/src/app/flows/flow/flow.service.ts@@ -428,42 +428,46 @@ export const flowService = (log: FastifyBaseLogger) => ({case FlowOperationType.ADD_NOTE:case FlowOperationType.UPDATE_NOTE:case FlowOperationType.DELETE_NOTE: {- const lastVersion = await flowVersionService(- log,- ).getFlowVersionOrThrow({- flowId: id,- versionId: undefined,- })- await flowVersionService(log).applyOperation({- userId,- projectId,- platformId,- flowVersion: lastVersion,- userOperation: operation,- })+ await withDraftLock({ flowId: id, log, fn: async () => {+ const lastVersion = await flowVersionService(+ log,+ ).getFlowVersionOrThrow({+ flowId: id,+ versionId: undefined,+ })+ await flowVersionService(log).applyOperation({+ userId,+ projectId,+ platformId,+ flowVersion: lastVersion,+ userOperation: operation,+ })+ } })break}default: {- const { version: lastVersion, createdNewDraft } = await createNewDraftIfVersionIsPublished({- flowId: id,- projectId,- platformId,- userId,- log,- })- const { error } = await tryCatch(() => flowVersionService(log).applyOperation({- userId,- projectId,- platformId,- flowVersion: lastVersion,- userOperation: operation,- }))- if (!isNil(error)) {- if (createdNewDraft) {- await tryCatch(() => flowVersionRepo().delete({ id: lastVersion.id, flowId: id }))+ await withDraftLock({ flowId: id, log, fn: async () => {+ const { version: lastVersion, createdNewDraft } = await createNewDraftIfVersionIsPublished({+ flowId: id,+ projectId,+ platformId,+ userId,+ log,+ })+ const { error } = await tryCatch(() => flowVersionService(log).applyOperation({+ userId,+ projectId,+ platformId,+ flowVersion: lastVersion,+ userOperation: operation,+ }))+ if (!isNil(error)) {+ if (createdNewDraft) {+ await tryCatch(() => flowVersionRepo().delete({ id: lastVersion.id, flowId: id }))+ }+ throw error}- throw error- }+ } })}}@@ -789,6 +793,18 @@ const lockFlowVersionIfNotLocked = async ({}+async function withDraftLock({ flowId, log, fn }: {+ flowId: FlowId+ log: FastifyBaseLogger+ fn: () => Promise<void>+}): Promise<void> {+ await distributedLock(log).runExclusive({+ key: `flow-draft-update-${flowId}`,+ timeoutInSeconds: DRAFT_UPDATE_LOCK_TIMEOUT_SECONDS,+ fn,+ })+}+async function applyStatusChange(params: {id: FlowIdprojectId: ProjectId@@ -1083,3 +1099,5 @@ async function createNewDraftIfVersionIsPublished({}return { version: lastVersion, createdNewDraft }}++const DRAFT_UPDATE_LOCK_TIMEOUT_SECONDS = 60diff --git a/packages/server/api/test/integration/ce/flows/flow/flow-concurrent-edits.test.ts b/packages/server/api/test/integration/ce/flows/flow/flow-concurrent-edits.test.tsnew file mode 100644index 00000000000..b7698bbc657--- /dev/null+++ b/packages/server/api/test/integration/ce/flows/flow/flow-concurrent-edits.test.ts@@ -0,0 +1,53 @@+import { FlowActionType, FlowOperationType, flowStructureUtil, PopulatedFlow, UpdateActionRequest } from '@activepieces/shared'+import { FastifyInstance } from 'fastify'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { flowService } from '../../../../../src/app/flows/flow/flow.service'+import { createTestContext } from '../../../../helpers/test-context'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../../helpers/test-setup'++let app: FastifyInstance++beforeAll(async () => {+ app = await setupTestEnvironment()+})++afterAll(async () => {+ await teardownTestEnvironment()+})++function codeStep({ name, displayName }: { name: string, displayName: string }): UpdateActionRequest {+ return {+ type: FlowActionType.CODE,+ displayName,+ name,+ settings: { input: {}, sourceCode: { code: 'export const code = async () => true', packageJson: '{}' } },+ valid: true,+ skip: false,+ }+}++describe('concurrent draft edits', () => {+ it('keeps every edit when several steps are updated at the same time', async () => {+ const ctx = await createTestContext(app)+ const flow: PopulatedFlow = (await ctx.post('/v1/flows', { displayName: 'concurrent', projectId: ctx.project.id }, { query: { projectId: ctx.project.id } })).json()+ const stepNames = ['step_1', 'step_2', 'step_3', 'step_4', 'step_5', 'step_6']+ for (const [index, name] of stepNames.entries()) {+ const parentStep = index === 0 ? 'trigger' : stepNames[index - 1]+ await ctx.post(`/v1/flows/${flow.id}`, { type: FlowOperationType.ADD_ACTION, request: { parentStep, action: codeStep({ name, displayName: name }) } })+ }++ await Promise.all(stepNames.map((name) =>+ flowService(app.log).update({+ id: flow.id,+ projectId: ctx.project.id,+ platformId: ctx.platform.id,+ userId: ctx.user.id,+ operation: { type: FlowOperationType.UPDATE_ACTION, request: codeStep({ name, displayName: `${name} renamed` }) },+ }),+ ))++ const saved: PopulatedFlow = (await ctx.get(`/v1/flows/${flow.id}`)).json()+ const savedNames = stepNames.map((name) => flowStructureUtil.getStep(name, saved.version.trigger)?.displayName)+ expect(savedNames).toEqual(stepNames.map((name) => `${name} renamed`))+ })+})