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
feat(flows): notify open builder tabs when a flow draft changes (#16496)
Othman Abu Ajamieh817dfecc503e
diff --git a/bun.lock b/bun.lockindex bef5dacf7ae..ca0e0438d75 100644--- a/bun.lock+++ b/bun.lock@@ -167,7 +167,7 @@},"packages/core/shared": {"name": "@activepieces/shared",- "version": "0.203.0",+ "version": "0.206.0","dependencies": {"@activepieces/core-execution": "workspace:*","@activepieces/core-formula": "workspace:*",diff --git a/packages/core/shared/package.json b/packages/core/shared/package.jsonindex 10a14685ecd..5a70e126b95 100644--- a/packages/core/shared/package.json+++ b/packages/core/shared/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/shared",- "version": "0.205.0",+ "version": "0.206.0","type": "commonjs","sideEffects": false,"main": "./dist/src/index.js",diff --git a/packages/core/shared/src/lib/automation/websocket/index.ts b/packages/core/shared/src/lib/automation/websocket/index.tsindex ded23d3d470..8b5883dae27 100644--- a/packages/core/shared/src/lib/automation/websocket/index.ts+++ b/packages/core/shared/src/lib/automation/websocket/index.ts@@ -14,6 +14,7 @@ export enum WebsocketClientEvent {PRESENCE_UPDATED = 'PRESENCE_UPDATED',CHAT_MESSAGE_CHUNK = 'CHAT_MESSAGE_CHUNK',CHAT_PERSONALIZATION_PROGRESS = 'CHAT_PERSONALIZATION_PROGRESS',+ FLOW_DRAFT_UPDATED = 'FLOW_DRAFT_UPDATED',}export enum WebsocketServerEvent {@@ -71,6 +72,13 @@ export const PresenceUpdatedEvent = z.object({users: z.array(PresenceUser),})+export const FlowDraftUpdatedEvent = z.object({+ flowId: z.string(),+ editorSessionId: z.string().nullable(),+})++export const EDITOR_SESSION_ID_HEADER = 'x-ap-editor-session-id'+export type LockResourceRequest = z.infer<typeof LockResourceRequest>export type LockResourceResponse = z.infer<typeof LockResourceResponse>export type ResourceLockedEvent = z.infer<typeof ResourceLockedEvent>@@ -80,3 +88,4 @@ export type TestStepProgressEvent = UpdateStepProgressRequest | EmitTestStepProgexport type PresenceRequest = z.infer<typeof PresenceRequest>export type PresenceUser = z.infer<typeof PresenceUser>export type PresenceUpdatedEvent = z.infer<typeof PresenceUpdatedEvent>+export type FlowDraftUpdatedEvent = z.infer<typeof FlowDraftUpdatedEvent>diff --git a/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.controller.ts b/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.controller.tsindex e38e966c8ba..23109d7751d 100644--- a/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.controller.ts+++ b/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.controller.ts@@ -4,6 +4,7 @@ import { StatusCodes } from 'http-status-codes'import { z } from 'zod'import { ProjectResourceType } from '../../../core/security/authorization/common'import { securityAccess } from '../../../core/security/authorization/fastify-security'+import { editorSession } from '../../../flows/flow/editor-session'import { FlowApprovalRequestEntity } from './flow-approval-request.entity'import { flowApprovalRequestService } from './flow-approval-request.service'@@ -45,6 +46,7 @@ export const flowApprovalRequestController: FastifyPluginAsyncZod = async (app)requestId: req.params.id,projectId: req.projectId,request: req,+ editorSessionId: editorSession.idFromRequest(req),})return reply.status(StatusCodes.NO_CONTENT).send()})diff --git a/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.service.ts b/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.service.tsindex ee404f67683..c27ae4c9c87 100644--- a/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.service.ts+++ b/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.service.ts@@ -3,6 +3,7 @@ import { FastifyBaseLogger, FastifyRequest } from 'fastify'import { repoFactory } from '../../../core/db/repo-factory'import { transaction } from '../../../core/db/transaction'import { flowExecutionCache } from '../../../flows/flow/flow-execution-cache'+import { flowSideEffects } from '../../../flows/flow/flow-service-side-effects'import { flowService } from '../../../flows/flow/flow.service'import { flowVersionRepo, flowVersionService } from '../../../flows/flow-version/flow-version.service'import { applicationEvents } from '../../../helper/application-events'@@ -195,7 +196,7 @@ export const flowApprovalRequestService = (log: FastifyBaseLogger) => ({}},- async withdraw({ requestId, projectId, request }: WithdrawParams): Promise<void> {+ async withdraw({ requestId, projectId, request, editorSessionId }: WithdrawParams): Promise<void> {const approval = await this.getOneOrThrow({ requestId, projectId })assertStateIsPending(approval.state)@@ -214,6 +215,7 @@ export const flowApprovalRequestService = (log: FastifyBaseLogger) => ({assertRowsAffected(deleteResult.raw?.length)await flowVersionRepo(entityManager).update({ id: lockedVersion.id }, { state: FlowVersionState.DRAFT })})+ await flowSideEffects(log).onDraftWritten({ flowId: approval.flowId, projectId: approval.projectId, editorSessionId })applicationEvents(log).sendUserEvent(request, {action: ApplicationEventName.FLOW_APPROVAL_WITHDRAWN,@@ -326,6 +328,7 @@ type WithdrawParams = {requestId: ApIdprojectId: ProjectIdrequest: FastifyRequest+ editorSessionId: string | null}type ListParams = {diff --git a/packages/server/api/src/app/ee/platform/admin/deno-migration.service.ts b/packages/server/api/src/app/ee/platform/admin/deno-migration.service.tsindex 413158b05ce..e343cf7648e 100644--- a/packages/server/api/src/app/ee/platform/admin/deno-migration.service.ts+++ b/packages/server/api/src/app/ee/platform/admin/deno-migration.service.ts@@ -4,6 +4,7 @@ import { FastifyBaseLogger } from 'fastify'import { FindOptionsWhere, In } from 'typeorm'import { websocketService } from '../../../core/websockets.service'import { fileService } from '../../../file/file.service'+import { flowSideEffects } from '../../../flows/flow/flow-service-side-effects'import { flowRepo } from '../../../flows/flow/flow.repo'import { flowVersionRepo } from '../../../flows/flow-version/flow-version.service'import { projectService } from '../../../project/project-service'@@ -67,6 +68,9 @@ async function migrateFlow({ log, flow, useDeno }: { log: FastifyBaseLogger, floconst migrated = await setUseDenoOnVersion({ versionId, useDeno })versionsMigrated += migratedpublishedVersionMigrated = publishedVersionMigrated || (migrated > 0 && versionId === flow.publishedVersionId)+ if (migrated > 0 && versionId === latestVersion.id) {+ await flowSideEffects(log).onDraftWritten({ flowId: flow.id, projectId: flow.projectId, editorSessionId: null })+ }}if (publishedVersionMigrated && !isNil(flow.publishedVersionId)) {diff --git a/packages/server/api/src/app/flows/flow-version/piece-upgrade.service.ts b/packages/server/api/src/app/flows/flow-version/piece-upgrade.service.tsindex 4b53cbd0bdb..4058c1b8dde 100644--- a/packages/server/api/src/app/flows/flow-version/piece-upgrade.service.ts+++ b/packages/server/api/src/app/flows/flow-version/piece-upgrade.service.ts@@ -1,10 +1,11 @@-import { isNil, spreadIfDefined, unique } from '@activepieces/core-utils'+import { FlowId, isNil, spreadIfDefined, unique } from '@activepieces/core-utils'import { ApplicationEventName, Flow, FlowAction, FlowActionType, FlowPiecesUpgradedEvent, flowStructureUtil, FlowTrigger, FlowTriggerType, FlowVersion } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { repoFactory } from '../../core/db/repo-factory'import { AuditEventEntity } from '../../ee/audit-logs/audit-event-entity'import { applicationEvents } from '../../helper/application-events'import { projectService } from '../../project/project-service'+import { flowSideEffects } from '../flow/flow-service-side-effects'import { flowRepo } from '../flow/flow.repo'import { FlowVersionEntity } from './flow-version-entity'import { pieceUpgradeRegister } from './piece-upgrade-register'@@ -92,18 +93,19 @@ async function revertFlow({ flowId, log }: RevertFlowParams): Promise<FlowPieceUrevertsByVersion.set(eventData.flowVersionId, versionReverts)}+ const latestVersion = await findLatestVersion(flowId)const revertedSteps: UpgradedStep[] = []for (const [flowVersionId, versionReverts] of revertsByVersion) {const flowVersion = await flowVersionRepo().findOneBy({ id: flowVersionId, flowId })if (isNil(flowVersion)) {continue}- revertedSteps.push(...await revertFlowVersion({ flow, platformId, flowVersion, versionReverts, log }))+ revertedSteps.push(...await revertFlowVersion({ flow, platformId, flowVersion, versionReverts, isLatestVersion: flowVersion.id === latestVersion?.id, log }))}return { flowId, found: true, upgradedSteps: revertedSteps }}-async function revertFlowVersion({ flow, platformId, flowVersion, versionReverts, log }: RevertFlowVersionParams): Promise<UpgradedStep[]> {+async function revertFlowVersion({ flow, platformId, flowVersion, versionReverts, isLatestVersion, log }: RevertFlowVersionParams): Promise<UpgradedStep[]> {const steps = flowStructureUtil.getAllSteps(flowVersion.trigger)const applied = steps.flatMap((step) => {if (step.type !== FlowActionType.PIECE && step.type !== FlowTriggerType.PIECE) {@@ -145,6 +147,9 @@ async function revertFlowVersion({ flow, platformId, flowVersion, versionRevertslog.warn({ flowVersion: { id: flowVersion.id } }, '[pieceUpgradeService] flow version changed concurrently, skipping revert')return []}+ if (isLatestVersion) {+ await sendDraftPush({ flow, log })+ }applicationEvents(log).sendUserEvent({ platformId, projectId: flow.projectId }, {action: ApplicationEventName.FLOW_PIECES_REVERTED,@@ -169,7 +174,7 @@ async function upgradeFlow({ flowId, projectId, log }: UpgradeFlowParams): Promireturn { flowId, found: false, upgradedSteps: [] }}const platformId = await projectService(log).getPlatformId(flow.projectId)- const latestVersion = await flowVersionRepo().findOne({ where: { flowId }, order: { created: 'DESC' } })+ const latestVersion = await findLatestVersion(flowId)const versions = [latestVersion]if (!isNil(flow.publishedVersionId) && flow.publishedVersionId !== latestVersion?.id) {versions.push(await flowVersionRepo().findOneBy({ id: flow.publishedVersionId }))@@ -179,12 +184,20 @@ async function upgradeFlow({ flowId, projectId, log }: UpgradeFlowParams): Promiif (isNil(version)) {continue}- upgradedSteps.push(...await upgradeFlowVersion({ flow, platformId, flowVersion: version, log }))+ upgradedSteps.push(...await upgradeFlowVersion({ flow, platformId, flowVersion: version, isLatestVersion: version.id === latestVersion?.id, log }))}return { flowId, found: true, upgradedSteps }}-async function upgradeFlowVersion({ flow, platformId, flowVersion, log }: UpgradeFlowVersionParams): Promise<UpgradedStep[]> {+async function findLatestVersion(flowId: FlowId): Promise<FlowVersion | null> {+ return flowVersionRepo().findOne({ where: { flowId }, order: { created: 'DESC' } })+}++async function sendDraftPush({ flow, log }: SendDraftPushParams): Promise<void> {+ await flowSideEffects(log).onDraftWritten({ flowId: flow.id, projectId: flow.projectId, editorSessionId: null })+}++async function upgradeFlowVersion({ flow, platformId, flowVersion, isLatestVersion, log }: UpgradeFlowVersionParams): Promise<UpgradedStep[]> {const { newFlowVersion, decisions, upgraded } = await resolveFlowVersionUpgrades({ flowVersion, log })if (decisions.length === 0) {return []@@ -196,6 +209,9 @@ async function upgradeFlowVersion({ flow, platformId, flowVersion, log }: Upgradlog.warn({ flowVersion: { id: flowVersion.id } }, '[pieceUpgradeService] flow version changed concurrently, skipping upgrade')return []}+ if (isLatestVersion) {+ await sendDraftPush({ flow, log })+ }}await sendUpgradeAuditEvent({ platformId, projectId: flow.projectId, flowId: flow.id, flowVersionId: flowVersion.id, decisions, log })@@ -316,8 +332,9 @@ async function updateTriggerIfUnchanged({ flowVersion, newTrigger }: UpdateTrigg.set({ trigger: newTrigger }).where('id = :id', { id: flowVersion.id }).andWhere('trigger = CAST(:snapshot AS jsonb)', { snapshot: JSON.stringify(flowVersion.trigger) })+ .returning(['id']).execute()- return updateResult.affected === 1+ return updateResult.raw?.length === 1}function getUsedStepName(step: FlowAction | FlowTrigger): string | undefined {@@ -421,6 +438,11 @@ type SendUpgradeAuditEventParams = {log: FastifyBaseLogger}+type SendDraftPushParams = {+ flow: Flow+ log: FastifyBaseLogger+}+type UpdateTriggerIfUnchangedParams = {flowVersion: FlowVersionnewTrigger: FlowVersion['trigger']@@ -431,6 +453,7 @@ type RevertFlowVersionParams = {platformId: stringflowVersion: FlowVersionversionReverts: Map<string, StepRevert>+ isLatestVersion: booleanlog: FastifyBaseLogger}@@ -444,6 +467,7 @@ type UpgradeFlowVersionParams = {flow: FlowplatformId: stringflowVersion: FlowVersion+ isLatestVersion: booleanlog: FastifyBaseLogger}diff --git a/packages/server/api/src/app/flows/flow/editor-session.ts b/packages/server/api/src/app/flows/flow/editor-session.tsnew file mode 100644index 00000000000..614aa9de2cd--- /dev/null+++ b/packages/server/api/src/app/flows/flow/editor-session.ts@@ -0,0 +1,10 @@+import { ApId } from '@activepieces/core-utils'+import { EDITOR_SESSION_ID_HEADER } from '@activepieces/shared'+import { FastifyRequest } from 'fastify'++export const editorSession = {+ idFromRequest(request: FastifyRequest): string | null {+ const parsed = ApId.safeParse(request.headers[EDITOR_SESSION_ID_HEADER])+ return parsed.success ? parsed.data : null+ },+}diff --git a/packages/server/api/src/app/flows/flow/flow-service-side-effects.ts b/packages/server/api/src/app/flows/flow/flow-service-side-effects.tsindex a3d891e2b9e..e063a1f0154 100644--- a/packages/server/api/src/app/flows/flow/flow-service-side-effects.ts+++ b/packages/server/api/src/app/flows/flow/flow-service-side-effects.ts@@ -1,5 +1,5 @@-import { isNil, PlatformId, ProjectId } from '@activepieces/core-utils'-import { ApplicationEventName, FileType, Flow, FlowOperationRequest, FlowOperationType, FlowStatus, FlowVersion, PopulatedFlow } from '@activepieces/shared'+import { FlowId, isNil, PlatformId, ProjectId, tryCatch } from '@activepieces/core-utils'+import { ApplicationEventName, FileType, Flow, FlowDraftUpdatedEvent, FlowOperationRequest, FlowOperationType, FlowStatus, FlowVersion, PopulatedFlow, WebsocketClientEvent } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { applicationEvents, MetaInformation } from '../../helper/application-events'import { triggerSourceService } from '../../trigger/trigger-source/trigger-source-service'@@ -105,6 +105,17 @@ export const flowSideEffects = (log: FastifyBaseLogger) => ({})},+ async onDraftWritten({ flowId, projectId, editorSessionId }: OnDraftWrittenParams): Promise<void> {+ const { error } = await tryCatch(async () => {+ const { websocketService } = await import('../../core/websockets.service')+ const event: FlowDraftUpdatedEvent = { flowId, editorSessionId }+ websocketService.to(projectId).emit(WebsocketClientEvent.FLOW_DRAFT_UPDATED, event)+ })+ if (!isNil(error)) {+ log.error({ error, flow: { id: flowId }, project: { id: projectId } }, '[flowSideEffects#onDraftWritten] Could not send the Draft Push, the write is kept')+ }+ },+onDisabledByWorker({ flow, projectId, platformId }: OnDisabledByWorkerParams): void {applicationEvents(log).sendWorkerEvent({projectId,@@ -150,6 +161,12 @@ type OnOperationAppliedParams = FlowEventParams & {operation: FlowOperationRequest}+type OnDraftWrittenParams = {+ flowId: FlowId+ projectId: ProjectId+ editorSessionId: string | null+}+type OnDisabledByWorkerParams = {flow: PopulatedFlowprojectId: ProjectIddiff --git a/packages/server/api/src/app/flows/flow/flow.controller.ts b/packages/server/api/src/app/flows/flow/flow.controller.tsindex c2882c0e865..1cee6d0da01 100644--- a/packages/server/api/src/app/flows/flow/flow.controller.ts+++ b/packages/server/api/src/app/flows/flow/flow.controller.ts@@ -14,6 +14,7 @@ import { gitRepoService } from '../../ee/projects/project-release/git-sync/git-simport { networkUtils } from '../../helper/network-utils'import { userService } from '../../user/user-service'import { migrateFlowVersionTemplate } from '../flow-version/migrations'+import { editorSession } from './editor-session'import { FlowEntity } from './flow.entity'import { flowService } from './flow.service'@@ -95,6 +96,7 @@ export const flowController: FastifyPluginAsyncZod = async (app) => {operation: cleanOperation(request.body),previousFlow: flow,ip: networkUtils.clientIp(request),+ editorSessionId: editorSession.idFromRequest(request),})})diff --git a/packages/server/api/src/app/flows/flow/flow.service.ts b/packages/server/api/src/app/flows/flow/flow.service.tsindex bae6ca7bf1c..c21a40a6833 100644--- a/packages/server/api/src/app/flows/flow/flow.service.ts+++ b/packages/server/api/src/app/flows/flow/flow.service.ts@@ -32,6 +32,14 @@ import { flowRepo } from './flow.repo'const notDeleting = { operationStatus: Not(FlowOperationStatus.DELETING) }+const nonDraftOperationTypes: FlowOperationType[] = [+ FlowOperationType.CHANGE_STATUS,+ FlowOperationType.CHANGE_FOLDER,+ FlowOperationType.UPDATE_METADATA,+ FlowOperationType.UPDATE_MINUTES_SAVED,+ FlowOperationType.UPDATE_OWNER,+]+export const flowService = (log: FastifyBaseLogger) => ({async create({ projectId, request, externalId, ownerId, templateId, createdBy, ip, emitEvents = true }: CreateParams): Promise<PopulatedFlow> {await assertExternalIdIsUnique({ projectId, externalId })@@ -333,6 +341,7 @@ export const flowService = (log: FastifyBaseLogger) => ({ip,emitEvents = true,skipRequiredActionsCheck = false,+ editorSessionId = null,}: UpdateParams): Promise<PopulatedFlow> {const flowBeforeOperation = emitEvents? previousFlow ?? await this.getOnePopulatedOrThrow({ id, projectId })@@ -463,6 +472,10 @@ export const flowService = (log: FastifyBaseLogger) => ({}}+ if (isDraftWrite(operation.type)) {+ await flowSideEffects(log).onDraftWritten({ flowId: id, projectId, editorSessionId })+ }+const updatedFlow = await this.getOnePopulatedOrThrow({id,projectId,@@ -750,6 +763,10 @@ export const flowService = (log: FastifyBaseLogger) => ({})+function isDraftWrite(type: FlowOperationType): boolean {+ return !nonDraftOperationTypes.includes(type)+}+async function assertRequiredActionsPresent({ projectId, platformId, flowVersion, log }: AssertRequiredActionsParams): Promise<void> {const result = await flowPublishHooks.get(log).findMissingRequiredActions({ projectId, platformId, flowVersion })if (isNil(result)) {@@ -982,6 +999,7 @@ type UpdateParams = EventEmissionParams & {platformId: PlatformIdpreviousFlow?: PopulatedFlowskipRequiredActionsCheck?: boolean+ editorSessionId?: string | null}type UpdatePublishedVersionIdParams = {diff --git a/packages/server/api/test/helpers/draft-push.ts b/packages/server/api/test/helpers/draft-push.tsnew file mode 100644index 00000000000..e842e6b9b19--- /dev/null+++ b/packages/server/api/test/helpers/draft-push.ts@@ -0,0 +1,32 @@+import { WebsocketClientEvent } from '@activepieces/shared'+import { vi } from 'vitest'+import { websocketService } from '../../src/app/core/websockets.service'++function capture(): DraftPush[] {+ const pushes: DraftPush[] = []+ observe((push) => {+ pushes.push(push)+ })+ return pushes+}++function observe(onPush: (push: DraftPush) => void): void {+ const realTo = websocketService.to+ vi.spyOn(websocketService, 'to').mockImplementation((room) => {+ const operator = realTo(room)+ vi.spyOn(operator, 'emit').mockImplementation((event, ...args) => {+ if (event === WebsocketClientEvent.FLOW_DRAFT_UPDATED) {+ onPush({ room, payload: args[0] })+ }+ return true+ })+ return operator+ })+}++export const draftPushes = { capture, observe }++export type DraftPush = {+ room: string+ payload: unknown+}diff --git a/packages/server/api/test/integration/ce/flows/flow/flow-draft-push.test.ts b/packages/server/api/test/integration/ce/flows/flow/flow-draft-push.test.tsnew file mode 100644index 00000000000..98c6829ca5b--- /dev/null+++ b/packages/server/api/test/integration/ce/flows/flow/flow-draft-push.test.ts@@ -0,0 +1,287 @@+import {+ apId,+ EDITOR_SESSION_ID_HEADER,+ FlowOperationRequest,+ FlowOperationType,+ FlowStatus,+ FlowVersion,+ FlowVersionState,+ LATEST_FLOW_SCHEMA_VERSION,+ NoteColorVariant,+ PopulatedFlow,+ UncategorizedFolderId,+} from '@activepieces/shared'+import { FastifyInstance } from 'fastify'+import { StatusCodes } from 'http-status-codes'+import { websocketService } from '../../../../../src/app/core/websockets.service'+import { flowService } from '../../../../../src/app/flows/flow/flow.service'+import { db } from '../../../../helpers/db'+import { describeWithAuth } from '../../../../helpers/describe-with-auth'+import { draftPushes } from '../../../../helpers/draft-push'+import { createTestContext, TestContext } from '../../../../helpers/test-context'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../../helpers/test-setup'++let app: FastifyInstance++beforeAll(async () => {+ app = await setupTestEnvironment()+})++afterAll(async () => {+ await teardownTestEnvironment()+})++afterEach(() => {+ vi.restoreAllMocks()+})++describe('Draft Push', () => {+ describeWithAuth('POST /v1/flows/:id', () => app, (setup) => {+ it.each(draftWrites)('sends FLOW_DRAFT_UPDATED with the editor session id to the project room after $type', async ({ build }) => {+ const ctx = await setup()+ const flow = await createFlow(ctx)+ const pushes = draftPushes.capture()++ const response = await applyOperation({+ ctx,+ flowId: flow.id,+ operation: build(ctx),+ editorSessionId: savingTabSessionId,+ })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(pushes).toEqual([{+ room: ctx.project.id,+ payload: { flowId: flow.id, editorSessionId: savingTabSessionId },+ }])+ })++ it('sends a null editor session id when the request has no header', async () => {+ const ctx = await setup()+ const flow = await createFlow(ctx)+ const pushes = draftPushes.capture()++ const response = await applyOperation({+ ctx,+ flowId: flow.id,+ operation: { type: FlowOperationType.CHANGE_NAME, request: { displayName: 'Renamed' } },+ })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(pushes).toEqual([{+ room: ctx.project.id,+ payload: { flowId: flow.id, editorSessionId: null },+ }])+ })++ it('sends a null editor session id when the header is not an ApId', async () => {+ const ctx = await setup()+ const flow = await createFlow(ctx)+ const pushes = draftPushes.capture()++ const response = await applyOperation({+ ctx,+ flowId: flow.id,+ operation: { type: FlowOperationType.CHANGE_NAME, request: { displayName: 'Renamed' } },+ editorSessionId: 'not-an-ap-id',+ })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(pushes).toEqual([{+ room: ctx.project.id,+ payload: { flowId: flow.id, editorSessionId: null },+ }])+ })++ it.each(nonDraftWrites)('sends no push for $type', async ({ build }) => {+ const ctx = await setup()+ const flow = await createFlow(ctx)+ const pushes = draftPushes.capture()++ const response = await applyOperation({+ ctx,+ flowId: flow.id,+ operation: build(ctx),+ editorSessionId: savingTabSessionId,+ })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(pushes).toEqual([])+ })++ it('sends a push when an edit on a published flow makes a new draft', async () => {+ const ctx = await setup()+ const flow = await createFlow(ctx)+ const publishResponse = await applyOperation({+ ctx,+ flowId: flow.id,+ operation: { type: FlowOperationType.LOCK_AND_PUBLISH, request: { status: FlowStatus.DISABLED } },+ })+ expect(publishResponse.statusCode).toBe(StatusCodes.OK)+ const pushes = draftPushes.capture()++ const response = await applyOperation({+ ctx,+ flowId: flow.id,+ operation: { type: FlowOperationType.CHANGE_NAME, request: { displayName: 'Edited after publish' } },+ editorSessionId: savingTabSessionId,+ })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(response.json().version.state).toBe(FlowVersionState.DRAFT)+ expect(pushes).toEqual([{+ room: ctx.project.id,+ payload: { flowId: flow.id, editorSessionId: savingTabSessionId },+ }])+ })++ it('sends the push after the draft is saved', async () => {+ const ctx = await setup()+ const flow = await createFlow(ctx)+ const draftNamesAtPush: Promise<string[]>[] = []+ draftPushes.observe(() => {+ draftNamesAtPush.push(readDraftNames(flow.id))+ })++ await applyOperation({+ ctx,+ flowId: flow.id,+ operation: { type: FlowOperationType.CHANGE_NAME, request: { displayName: 'Saved before the push' } },+ })++ expect(await Promise.all(draftNamesAtPush)).toEqual([['Saved before the push']])+ })+ })++ describe('flowService.update', () => {+ it('sends a push with a null editor session id when emitEvents is false', async () => {+ const ctx = await createTestContext(app)+ const flow = await createFlow(ctx)+ const pushes = draftPushes.capture()++ await flowService(app.log).update({+ id: flow.id,+ projectId: ctx.project.id,+ platformId: ctx.platform.id,+ operation: { type: FlowOperationType.CHANGE_NAME, request: { displayName: 'Renamed by a release' } },+ emitEvents: false,+ })++ expect(pushes).toEqual([{+ room: ctx.project.id,+ payload: { flowId: flow.id, editorSessionId: null },+ }])+ })++ it('logs one error line and still saves when the push throws', async () => {+ const ctx = await createTestContext(app)+ const flow = await createFlow(ctx)+ const pushError = new Error('socket server is down')+ vi.spyOn(websocketService, 'to').mockImplementation(() => {+ throw pushError+ })+ const logError = vi.spyOn(app.log, 'error')++ const updatedFlow = await flowService(app.log).update({+ id: flow.id,+ projectId: ctx.project.id,+ platformId: ctx.platform.id,+ operation: { type: FlowOperationType.CHANGE_NAME, request: { displayName: 'Saved without a push' } },+ })++ expect(updatedFlow.version.displayName).toBe('Saved without a push')+ expect(logError).toHaveBeenCalledTimes(1)+ expect(logError).toHaveBeenCalledWith(+ { error: pushError, flow: { id: flow.id }, project: { id: ctx.project.id } },+ expect.stringMatching(/^\[flowSideEffects#onDraftWritten\] /),+ )+ })+ })++ describe('writes that are not Draft Writes', () => {+ it('sends no push when a read migrates the draft to the latest schema version', async () => {+ const ctx = await createTestContext(app)+ const flow = await createFlow(ctx)+ await db.update('flow_version', flow.version.id, { schemaVersion: '20' })+ const pushes = draftPushes.capture()++ const response = await ctx.get(`/v1/flows/${flow.id}`)++ expect(response.statusCode).toBe(StatusCodes.OK)+ const storedVersion = await db.findOneByOrFail<FlowVersion>('flow_version', { id: flow.version.id })+ expect(storedVersion.schemaVersion).toBe(LATEST_FLOW_SCHEMA_VERSION)+ expect(pushes).toEqual([])+ })++ it('sends no push when a new flow gets its empty draft', async () => {+ const ctx = await createTestContext(app)+ const pushes = draftPushes.capture()++ await createFlow(ctx)++ expect(pushes).toEqual([])+ })++ it('sends no push when a flow is deleted', async () => {+ const ctx = await createTestContext(app)+ const flow = await createFlow(ctx)+ const pushes = draftPushes.capture()++ const response = await ctx.delete(`/v1/flows/${flow.id}`)++ expect(response.statusCode).toBe(StatusCodes.NO_CONTENT)+ expect(pushes).toEqual([])+ })+ })+})++const savingTabSessionId = apId()++const draftWrites: WriteCase[] = [+ { type: FlowOperationType.CHANGE_NAME, build: () => ({ type: FlowOperationType.CHANGE_NAME, request: { displayName: 'Renamed' } }) },+ { type: FlowOperationType.LOCK_AND_PUBLISH, build: () => ({ type: FlowOperationType.LOCK_AND_PUBLISH, request: { status: FlowStatus.DISABLED } }) },+ { type: FlowOperationType.ADD_NOTE, build: () => ({ type: FlowOperationType.ADD_NOTE, request: { id: 'note-1', content: 'A note', color: NoteColorVariant.YELLOW, position: { x: 0, y: 0 }, size: { width: 200, height: 100 } } }) },+]++const nonDraftWrites: WriteCase[] = [+ { type: FlowOperationType.CHANGE_STATUS, build: () => ({ type: FlowOperationType.CHANGE_STATUS, request: { status: FlowStatus.DISABLED } }) },+ { type: FlowOperationType.CHANGE_FOLDER, build: () => ({ type: FlowOperationType.CHANGE_FOLDER, request: { folderId: UncategorizedFolderId } }) },+ { type: FlowOperationType.UPDATE_METADATA, build: () => ({ type: FlowOperationType.UPDATE_METADATA, request: { metadata: { source: 'test' } } }) },+ { type: FlowOperationType.UPDATE_MINUTES_SAVED, build: () => ({ type: FlowOperationType.UPDATE_MINUTES_SAVED, request: { timeSavedPerRun: 5 } }) },+ { type: FlowOperationType.UPDATE_OWNER, build: (ctx) => ({ type: FlowOperationType.UPDATE_OWNER, request: { ownerId: ctx.user.id } }) },+]++async function createFlow(ctx: TestContext): Promise<PopulatedFlow> {+ const response = await ctx.post('/v1/flows', {+ displayName: 'Draft Push flow',+ projectId: ctx.project.id,+ }, { query: { projectId: ctx.project.id } })+ expect(response.statusCode).toBe(StatusCodes.CREATED)+ return response.json()+}++function applyOperation({ ctx, flowId, operation, editorSessionId }: ApplyOperationParams): ReturnType<FastifyInstance['inject']> {+ return ctx.inject({+ method: 'POST',+ url: `/api/v1/flows/${flowId}`,+ headers: editorSessionId === undefined ? {} : { [EDITOR_SESSION_ID_HEADER]: editorSessionId },+ body: operation,+ })+}++async function readDraftNames(flowId: string): Promise<string[]> {+ const versions = await db.findBy<FlowVersion>('flow_version', { flowId })+ return versions.map((version) => version.displayName)+}++type ApplyOperationParams = {+ ctx: TestContext+ flowId: string+ operation: FlowOperationRequest+ editorSessionId?: string+}++type WriteCase = {+ type: FlowOperationType+ build: (ctx: TestContext) => FlowOperationRequest+}diff --git a/packages/server/api/test/integration/cloud/flow/migrate-to-deno.test.ts b/packages/server/api/test/integration/cloud/flow/migrate-to-deno.test.tsindex cc468dc3c09..5772391722b 100644--- a/packages/server/api/test/integration/cloud/flow/migrate-to-deno.test.ts+++ b/packages/server/api/test/integration/cloud/flow/migrate-to-deno.test.ts@@ -1,9 +1,11 @@-import { apId } from '@activepieces/core-utils'+import { apId, spreadIfDefined } from '@activepieces/core-utils'import { CodeAction, Flow, FlowAction, FlowActionType, FlowStatus, flowStructureUtil, FlowTrigger, FlowTriggerType, FlowVersion, FlowVersionState } from '@activepieces/shared'import dayjs from 'dayjs'import { FastifyInstance } from 'fastify'import { StatusCodes } from 'http-status-codes'+import { flowVersionRepo } from '../../../../src/app/flows/flow-version/flow-version.service'import { db } from '../../../helpers/db'+import { draftPushes } from '../../../helpers/draft-push'import { createMockFlow, createMockFlowVersion } from '../../../helpers/mocks'import { createTestContext, TestContext } from '../../../helpers/test-context'import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'@@ -18,7 +20,11 @@ afterAll(async () => {await teardownTestEnvironment()})-function buildTriggerWithCodeStep(): FlowTrigger {+afterEach(() => {+ vi.restoreAllMocks()+})++function buildTriggerWithCodeStep({ useDeno }: { useDeno?: boolean } = {}): FlowTrigger {const codeStep: FlowAction = {type: FlowActionType.CODE,name: 'step_1',@@ -31,6 +37,7 @@ function buildTriggerWithCodeStep(): FlowTrigger {},input: {},errorHandlingOptions: {},+ ...spreadIfDefined('useDeno', useDeno),},}return {@@ -92,6 +99,33 @@ async function setupFlowWithPublishedLatestVersion(ctx: TestContext) {return { flow, publishedVersion }}+async function setupFlowWithMigratedDraftAndLegacyPublishedVersion(ctx: TestContext) {+ const flowId = apId()+ const publishedVersion = createMockFlowVersion({+ flowId,+ state: FlowVersionState.LOCKED,+ trigger: buildTriggerWithCodeStep(),+ created: dayjs().subtract(1, 'hour').toISOString(),+ })+ const draftVersion = createMockFlowVersion({+ flowId,+ state: FlowVersionState.DRAFT,+ trigger: buildTriggerWithCodeStep({ useDeno: true }),+ created: dayjs().toISOString(),+ })+ const flow = createMockFlow({+ id: flowId,+ projectId: ctx.project.id,+ status: FlowStatus.DISABLED,+ publishedVersionId: null,+ })+ await db.save('flow', flow)+ await db.save('flow_version', publishedVersion)+ await db.save('flow_version', draftVersion)+ await db.update('flow', flowId, { publishedVersionId: publishedVersion.id })+ return { flow, draftVersion, publishedVersion }+}+function getCodeStep(flowVersion: FlowVersion): CodeAction | undefined {return flowStructureUtil.getAllSteps(flowVersion.trigger)@@ -224,3 +258,86 @@ describe('POST /v1/admin/flows/migrate-to-deno', () => {expect(response.statusCode).toBe(StatusCodes.FORBIDDEN)})})++describe('Draft Push after the Deno migration', () => {+ it('sends a Draft Push with a null editor session id for each flow whose draft it changes', async () => {+ const ctx = await createTestContext(app!)+ const { flow: firstFlow } = await setupFlowWithDraftAndPublishedVersions(ctx)+ const { flow: secondFlow } = await setupFlowWithDraftAndPublishedVersions(ctx)+ const pushes = draftPushes.capture()++ const response = await postMigrateToDeno({ projectId: ctx.project.id })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(pushes).toHaveLength(2)+ expect(pushes).toEqual(expect.arrayContaining([+ { room: ctx.project.id, payload: { flowId: firstFlow.id, editorSessionId: null } },+ { room: ctx.project.id, payload: { flowId: secondFlow.id, editorSessionId: null } },+ ]))+ })++ it('sends a Draft Push when the latest version is the published version', async () => {+ const ctx = await createTestContext(app!)+ const { flow } = await setupFlowWithPublishedLatestVersion(ctx)+ const pushes = draftPushes.capture()++ const response = await postMigrateToDeno({ flowIds: [flow.id] })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(pushes).toEqual([{ room: ctx.project.id, payload: { flowId: flow.id, editorSessionId: null } }])+ })++ it('sends no push when the migration changes only the published version', async () => {+ const ctx = await createTestContext(app!)+ const { flow } = await setupFlowWithMigratedDraftAndLegacyPublishedVersion(ctx)+ const pushes = draftPushes.capture()++ const response = await postMigrateToDeno({ flowIds: [flow.id] })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(response.json()).toEqual({ flowsProcessed: 1, flowVersionsMigrated: 1, notifiedFlows: 1 })+ expect(pushes).toEqual([])+ })++ it('sends a Draft Push when revert-from-deno changes the draft', async () => {+ const ctx = await createTestContext(app!)+ const { flow } = await setupFlowWithDraftAndPublishedVersions(ctx)+ await postMigrateToDeno({ flowIds: [flow.id] })+ const pushes = draftPushes.capture()++ const response = await postRevertFromDeno({ flowIds: [flow.id] })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(pushes).toEqual([{ room: ctx.project.id, payload: { flowId: flow.id, editorSessionId: null } }])+ })++ it('sends a Draft Push when the published version fails after the draft was migrated', async () => {+ const ctx = await createTestContext(app!)+ const { flow, publishedVersion } = await setupFlowWithDraftAndPublishedVersions(ctx)+ const repo = flowVersionRepo()+ const realFindOneBy = repo.findOneBy.bind(repo)+ vi.spyOn(repo, 'findOneBy').mockImplementation(async (where) => {+ if (!Array.isArray(where) && where.id === publishedVersion.id) {+ throw new Error('the published version cannot be read')+ }+ return realFindOneBy(where)+ })+ const pushes = draftPushes.capture()++ const response = await postMigrateToDeno({ flowIds: [flow.id] })++ expect(response.statusCode).toBe(StatusCodes.INTERNAL_SERVER_ERROR)+ expect(pushes).toEqual([{ room: ctx.project.id, payload: { flowId: flow.id, editorSessionId: null } }])+ })++ it('sends no push when a second run changes nothing', async () => {+ const ctx = await createTestContext(app!)+ const { flow } = await setupFlowWithDraftAndPublishedVersions(ctx)+ await postMigrateToDeno({ flowIds: [flow.id] })+ const pushes = draftPushes.capture()++ await postMigrateToDeno({ flowIds: [flow.id] })++ expect(pushes).toEqual([])+ })+})diff --git a/packages/server/api/test/integration/cloud/flow/piece-upgrade.test.ts b/packages/server/api/test/integration/cloud/flow/piece-upgrade.test.tsnew file mode 100644index 00000000000..188a931f5be--- /dev/null+++ b/packages/server/api/test/integration/cloud/flow/piece-upgrade.test.ts@@ -0,0 +1,293 @@+import { apId } from '@activepieces/core-utils'+import { ApplicationEventName, Flow, FlowStatus, FlowTrigger, FlowTriggerType, FlowVersion, FlowVersionState } from '@activepieces/shared'+import dayjs, { Dayjs } from 'dayjs'+import { FastifyInstance, LightMyRequestResponse } from 'fastify'+import { StatusCodes } from 'http-status-codes'+import { pieceUpgradeRegister } from '../../../../src/app/flows/flow-version/piece-upgrade-register'+import { db } from '../../../helpers/db'+import { draftPushes } from '../../../helpers/draft-push'+import { createMockFlow, createMockFlowVersion } from '../../../helpers/mocks'+import { createTestContext, TestContext } from '../../../helpers/test-context'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'++let app: FastifyInstance | null = null++beforeAll(async () => {+ app = await setupTestEnvironment()+})++afterAll(async () => {+ await teardownTestEnvironment()+})++beforeEach(() => {+ vi.spyOn(pieceUpgradeRegister, 'lookup').mockImplementation(async ({ pieceName, pieceVersion }) =>+ pieceName === WEBHOOK_PIECE_NAME && pieceVersion === OLD_WEBHOOK_VERSION+ ? { target: NEW_WEBHOOK_VERSION }+ : undefined)+})++afterEach(() => {+ vi.restoreAllMocks()+})++describe('POST /v1/admin/flows/upgrade-pieces', () => {+ it('sends a Draft Push with a null editor session id when the upgrade changes the draft', async () => {+ const ctx = await createTestContext(app!)+ const { flow } = await seedDraftFlow({ ctx, pieceVersion: OLD_WEBHOOK_VERSION })+ const pushes = draftPushes.capture()++ const response = await postAdminFlowsEndpoint({ route: 'upgrade-pieces', body: { flowIds: [flow.id] } })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(response.json()[0].upgradedSteps).toHaveLength(1)+ expect(pushes).toEqual([{+ room: ctx.project.id,+ payload: { flowId: flow.id, editorSessionId: null },+ }])+ })++ it('sends a push only for the flow whose draft it changes', async () => {+ const ctx = await createTestContext(app!)+ const { flow: upgradedFlow } = await seedDraftFlow({ ctx, pieceVersion: OLD_WEBHOOK_VERSION })+ const { flow: currentFlow } = await seedDraftFlow({ ctx, pieceVersion: NEW_WEBHOOK_VERSION })+ const pushes = draftPushes.capture()++ const response = await postAdminFlowsEndpoint({ route: 'upgrade-pieces', body: { flowIds: [upgradedFlow.id, currentFlow.id] } })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(pushes).toEqual([{+ room: ctx.project.id,+ payload: { flowId: upgradedFlow.id, editorSessionId: null },+ }])+ })++ it('sends a Draft Push when the latest version is the published version', async () => {+ const ctx = await createTestContext(app!)+ const { flow } = await seedPublishedFlow({ ctx, pieceVersion: OLD_WEBHOOK_VERSION })+ const pushes = draftPushes.capture()++ const response = await postAdminFlowsEndpoint({ route: 'upgrade-pieces', body: { flowIds: [flow.id] } })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(pushes).toEqual([{+ room: ctx.project.id,+ payload: { flowId: flow.id, editorSessionId: null },+ }])+ })++ it('sends no push when the upgrade changes only the published version', async () => {+ const ctx = await createTestContext(app!)+ const { flow, publishedVersion } = await seedPublishedFlowWithDraft({+ ctx,+ publishedPieceVersion: OLD_WEBHOOK_VERSION,+ draftPieceVersion: NEW_WEBHOOK_VERSION,+ })+ const pushes = draftPushes.capture()++ const response = await postAdminFlowsEndpoint({ route: 'upgrade-pieces', body: { flowIds: [flow.id] } })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(response.json()[0].upgradedSteps).toEqual([expect.objectContaining({ flowVersionId: publishedVersion.id })])+ expect(pushes).toEqual([])+ })++ it('sends the Draft Push when the published version fails after the draft was upgraded', async () => {+ const ctx = await createTestContext(app!)+ const { flow } = await seedPublishedFlowWithDraft({+ ctx,+ publishedPieceVersion: OLD_WEBHOOK_VERSION,+ draftPieceVersion: OLD_WEBHOOK_VERSION,+ })+ let lookups = 0+ vi.spyOn(pieceUpgradeRegister, 'lookup').mockImplementation(async () => {+ lookups += 1+ if (lookups > 1) {+ throw new Error('the upgrade register is unavailable')+ }+ return { target: NEW_WEBHOOK_VERSION }+ })+ const pushes = draftPushes.capture()++ const response = await postAdminFlowsEndpoint({ route: 'upgrade-pieces', body: { flowIds: [flow.id] } })++ expect(response.statusCode).toBe(StatusCodes.INTERNAL_SERVER_ERROR)+ expect(pushes).toEqual([{+ room: ctx.project.id,+ payload: { flowId: flow.id, editorSessionId: null },+ }])+ })+})++describe('POST /v1/admin/flows/revert-upgrade', () => {+ it('sends a Draft Push with a null editor session id when the revert changes the draft', async () => {+ const ctx = await createTestContext(app!)+ const { flow, draftVersion } = await seedDraftFlow({ ctx, pieceVersion: NEW_WEBHOOK_VERSION })+ await seedUpgradeAuditEvent({ ctx, flowId: flow.id, flowVersionId: draftVersion.id })+ const pushes = draftPushes.capture()++ const response = await postAdminFlowsEndpoint({ route: 'revert-upgrade', body: { flowIds: [flow.id] } })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(response.json()[0].upgradedSteps).toHaveLength(1)+ expect(pushes).toEqual([{+ room: ctx.project.id,+ payload: { flowId: flow.id, editorSessionId: null },+ }])+ })++ it('sends no push when the revert changes only the published version', async () => {+ const ctx = await createTestContext(app!)+ const { flow, publishedVersion } = await seedPublishedFlowWithDraft({+ ctx,+ publishedPieceVersion: NEW_WEBHOOK_VERSION,+ draftPieceVersion: NEW_WEBHOOK_VERSION,+ })+ await seedUpgradeAuditEvent({ ctx, flowId: flow.id, flowVersionId: publishedVersion.id })+ const pushes = draftPushes.capture()++ const response = await postAdminFlowsEndpoint({ route: 'revert-upgrade', body: { flowIds: [flow.id] } })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(response.json()[0].upgradedSteps).toEqual([expect.objectContaining({ flowVersionId: publishedVersion.id })])+ expect(pushes).toEqual([])+ })+})++async function seedDraftFlow({ ctx, pieceVersion }: SeedDraftFlowParams): Promise<DraftFlow> {+ const flow = createMockFlow({ projectId: ctx.project.id, status: FlowStatus.DISABLED, publishedVersionId: null })+ await db.save('flow', flow)+ const draftVersion = await saveVersion({ flowId: flow.id, state: FlowVersionState.DRAFT, pieceVersion, created: dayjs() })+ return { flow, draftVersion }+}++async function seedPublishedFlow({ ctx, pieceVersion }: SeedPublishedFlowParams): Promise<PublishedFlow> {+ const flow = createMockFlow({ projectId: ctx.project.id, status: FlowStatus.DISABLED, publishedVersionId: null })+ await db.save('flow', flow)+ const publishedVersion = await saveVersion({ flowId: flow.id, state: FlowVersionState.LOCKED, pieceVersion, created: dayjs() })+ await db.update('flow', flow.id, { publishedVersionId: publishedVersion.id })+ return { flow, publishedVersion }+}++async function seedPublishedFlowWithDraft({ ctx, publishedPieceVersion, draftPieceVersion }: SeedPublishedFlowWithDraftParams): Promise<PublishedFlowWithDraft> {+ const flow = createMockFlow({ projectId: ctx.project.id, status: FlowStatus.DISABLED, publishedVersionId: null })+ await db.save('flow', flow)+ const publishedVersion = await saveVersion({ flowId: flow.id, state: FlowVersionState.LOCKED, pieceVersion: publishedPieceVersion, created: dayjs().subtract(1, 'hour') })+ await db.update('flow', flow.id, { publishedVersionId: publishedVersion.id })+ const draftVersion = await saveVersion({ flowId: flow.id, state: FlowVersionState.DRAFT, pieceVersion: draftPieceVersion, created: dayjs() })+ return { flow, draftVersion, publishedVersion }+}++async function saveVersion({ flowId, state, pieceVersion, created }: SaveVersionParams): Promise<FlowVersion> {+ const version = createMockFlowVersion({+ flowId,+ state,+ trigger: webhookTrigger(pieceVersion),+ created: created.toISOString(),+ })+ await db.save('flow_version', version)+ return version+}++async function seedUpgradeAuditEvent({ ctx, flowId, flowVersionId }: SeedUpgradeAuditEventParams): Promise<void> {+ const now = dayjs().toISOString()+ await db.save('audit_event', {+ id: apId(),+ created: now,+ updated: now,+ platformId: ctx.platform.id,+ projectId: ctx.project.id,+ action: ApplicationEventName.FLOW_PIECES_UPGRADED,+ data: {+ flowId,+ flowVersionId,+ steps: [{+ stepName: 'trigger',+ actionOrTriggerName: 'catch_webhook',+ decision: 'UPGRADED',+ prevVersion: OLD_WEBHOOK_VERSION,+ newVersion: NEW_WEBHOOK_VERSION,+ }],+ },+ })+}++function webhookTrigger(pieceVersion: string): FlowTrigger {+ return {+ name: 'trigger',+ valid: true,+ displayName: 'Catch Webhook',+ lastUpdatedDate: dayjs().toISOString(),+ type: FlowTriggerType.PIECE,+ settings: {+ pieceName: WEBHOOK_PIECE_NAME,+ pieceVersion,+ triggerName: 'catch_webhook',+ input: {},+ propertySettings: {},+ },+ }+}++function postAdminFlowsEndpoint({ route, body }: PostAdminFlowsEndpointParams): Promise<LightMyRequestResponse> {+ return app!.inject({+ method: 'POST',+ url: `/api/v1/admin/flows/${route}`,+ headers: {+ 'api-key': 'api-key',+ },+ body,+ })+}++const WEBHOOK_PIECE_NAME = '@activepieces/piece-webhook'+const OLD_WEBHOOK_VERSION = '0.1.33'+const NEW_WEBHOOK_VERSION = '0.1.36'++type SeedDraftFlowParams = {+ ctx: TestContext+ pieceVersion: string+}++type DraftFlow = {+ flow: Flow+ draftVersion: FlowVersion+}++type SeedPublishedFlowParams = {+ ctx: TestContext+ pieceVersion: string+}++type PublishedFlow = {+ flow: Flow+ publishedVersion: FlowVersion+}++type SeedPublishedFlowWithDraftParams = {+ ctx: TestContext+ publishedPieceVersion: string+ draftPieceVersion: string+}++type PublishedFlowWithDraft = DraftFlow & {+ publishedVersion: FlowVersion+}++type SaveVersionParams = {+ flowId: string+ state: FlowVersionState+ pieceVersion: string+ created: Dayjs+}++type PostAdminFlowsEndpointParams = {+ route: string+ body: Record<string, unknown>+}++type SeedUpgradeAuditEventParams = {+ ctx: TestContext+ flowId: string+ flowVersionId: string+}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.tsindex 80a3fd7fb72..e64fb50a2a8 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@@ -1,6 +1,7 @@import {apId,DefaultProjectRole,+ EDITOR_SESSION_ID_HEADER,Flow,FlowApprovalRequest,FlowApprovalRequestState,@@ -11,10 +12,11 @@ import {} from '@activepieces/shared'import { FastifyInstance } from 'fastify'import { StatusCodes } from 'http-status-codes'-import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'import { flowApprovalRequestService } from '../../../../src/app/ee/flows/flow-approval/flow-approval-request.service'import { eeFlowPublishHook } from '../../../../src/app/ee/flows/flow-approval/flow-publish-hook'import { db } from '../../../helpers/db'+import { DraftPush, draftPushes } from '../../../helpers/draft-push'import {createMockFlow,createMockFlowVersion,@@ -92,6 +94,11 @@ async function seedPendingApproval(ctx: TestContext, submitterId: string): Promireturn { flow, version, approval }}+async function readVersionState(versionId: string): Promise<FlowVersionState> {+ const storedVersion = await db.findOneByOrFail<FlowVersion>('flow_version', { id: versionId })+ return storedVersion.state+}+describe('flow-approval — routing', () => {it('returns PUBLISH_NOW when environments are disabled', async () => {const ctx = await createTestContext(app!, {@@ -338,6 +345,73 @@ describe('flow-approval — withdraw', () => {const reloadedVersion = await db.findOneByOrFail<FlowVersion>('flow_version', { id: version.id })expect(reloadedVersion.state).toBe(FlowVersionState.DRAFT)})++ describe('Draft Push', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('sends a Draft Push with the editor session id after the version returns to DRAFT', async () => {+ const ctx = await setupSensitiveCtx()+ const memberCtx = await createMemberContext(app!, ctx, {+ projectRole: DefaultProjectRole.EDITOR,+ })+ const { flow, version, approval } = await seedPendingApproval(ctx, memberCtx.user.id)+ const editorSessionId = apId()+ const pushes: DraftPush[] = []+ const versionStatesAtPush: Promise<FlowVersionState>[] = []+ draftPushes.observe((push) => {+ pushes.push(push)+ versionStatesAtPush.push(readVersionState(version.id))+ })++ const response = await memberCtx.inject({+ method: 'POST',+ url: `/api/v1/flow-approval-requests/${approval.id}/withdraw`,+ headers: { [EDITOR_SESSION_ID_HEADER]: editorSessionId },+ body: {},+ })++ expect(response.statusCode).toBe(StatusCodes.NO_CONTENT)+ expect(pushes).toEqual([{+ room: ctx.project.id,+ payload: { flowId: flow.id, editorSessionId },+ }])+ expect(await Promise.all(versionStatesAtPush)).toEqual([FlowVersionState.DRAFT])+ })++ it('sends a null editor session id when the request has no header', async () => {+ const ctx = await setupSensitiveCtx()+ const memberCtx = await createMemberContext(app!, ctx, {+ projectRole: DefaultProjectRole.EDITOR,+ })+ const { flow, approval } = await seedPendingApproval(ctx, memberCtx.user.id)+ const pushes = draftPushes.capture()++ const response = await memberCtx.post(`/v1/flow-approval-requests/${approval.id}/withdraw`, {})++ expect(response?.statusCode).toBe(StatusCodes.NO_CONTENT)+ expect(pushes).toEqual([{+ room: ctx.project.id,+ payload: { flowId: flow.id, editorSessionId: null },+ }])+ })++ it('sends no push when the request is no longer pending', async () => {+ const ctx = await setupSensitiveCtx()+ const memberCtx = await createMemberContext(app!, ctx, {+ projectRole: DefaultProjectRole.EDITOR,+ })+ const { approval } = await seedPendingApproval(ctx, memberCtx.user.id)+ await db.update('flow_approval_request', approval.id, { state: FlowApprovalRequestState.REJECTED })+ const pushes = draftPushes.capture()++ const response = await memberCtx.post(`/v1/flow-approval-requests/${approval.id}/withdraw`, {})++ expect(response?.statusCode).toBe(StatusCodes.CONFLICT)+ expect(pushes).toEqual([])+ })+ })})describe('flow-approval — module gating', () => {