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): releases and project replace now apply changed connections instead of reverting them (#14899)

Bartosz Majewski5a885e66b06e
diff --git a/brain/knowledge/engineering/ci-pr-review-hygiene.md b/brain/knowledge/engineering/ci-pr-review-hygiene.md
index ba558cbf257..cfa81955d6e 100644
--- a/brain/knowledge/engineering/ci-pr-review-hygiene.md
+++ b/brain/knowledge/engineering/ci-pr-review-hygiene.md
@@ -61,6 +61,7 @@ Enforcement is the **`Codeowners review` repository ruleset** (active on the def
- **`license/cla` keys off the commit author email, so re-opening someone else's branch under your own name does not clear it.** CLA-assistant walks every commit in the PR rather than the PR author, and an author email that matches no GitHub account can never be matched to a signature — the 47 commits carried over onto [#15092](https://github.com/activepieces/activepieces/pull/15092) were authored as `[email protected]`, a local hostname, so the check sat at `not_signed` on a PR opened by a member. It is not in the `main` ruleset's required-checks list, but it is red on the page and a reviewer reads that as unmergeable. Either the original author signs through the PR link, or the commits get re-authored to an email tied to their GitHub account before you open it.
- **A branch that predates the `brain/` → `brain/knowledge/` move cannot edit a brain page in place — GitHub will call the PR conflicting even when `git merge` is clean locally.** Git follows the rename and merges the modification into the new path; GitHub's mergeability check does not, so it reports `modify/delete` on the old path and the PR goes `dirty`. Local `git merge-tree --write-tree` exits 0 and hides the problem; reproduce what GitHub sees with `git merge -X no-renames origin/main`. Fix: merge `origin/main` into the branch first, which lands the edit at the new path, then push.
- **`breaking-change-check` couples the docs entry to the label in BOTH directions, so back-documenting an already-shipped change drags the label onto a docs-only PR.** R3 in `tools/scripts/breaking-change-check.ts` fails a PR that adds a `####` entry to `docs/install/reference/breaking-changes.mdx` without `⛓️‍💥 breaking-change`, exactly as it fails the label without an entry — and the template answer has to agree too, so "yes" must be ticked on a PR that changes no code. It reads the *added lines of that one file* from `git diff origin/<base>...HEAD`, and `hasBreakingEntry` wants a `####` heading **plus** a non-heading body line, so a heading alone, a `---`, or a version bump does not count. Two consequences: the label then collides with `skip-changelog` in release-drafter (pick one deliberately — the feature's own PR usually already carried the changelog entry), and an entry appended to a *released* section still trips it, since the check never looks at which heading the lines landed under.
+- **A release cut empties `## Unreleased` into a version section, so a long-lived branch's entry conflicts in a way that is wrong to resolve by hand.** The entries do not move to the bottom of the file — the whole Unreleased block is relabelled as the new version and a fresh Unreleased is opened above it. A branch that added its entry weeks ago then conflicts against a section that has been relocated wholesale, and git presents it as "your entire block versus one stray line", which invites resolving the hunk in place. Doing that leaves the entry sitting inside an already-released section, where it is both wrong for readers and invisible to `breaking-change-check` (see the bullet above: the check never looks at which heading the added lines landed under, so CI stays green). Take main's copy of the file whole and re-insert the entry at the end of the *current* Unreleased section instead, then check that the entries you unioned on an earlier merge each appear exactly once — the previous resolution's placement is usually now a duplicate. Seen on GIT-1764 / #14899, which conflicted twice in one day for this reason.
- **Nothing rolls `## Unreleased` over at release time, and the docs site is unversioned — so a breaking-changes entry has to name its own version.** No workflow or script writes to `docs/install/reference/breaking-changes.mdx` (`breaking-change-check.ts` only reads it), and `git log -S"## 0.88"` on the file comes back empty: the heading has not moved since 0.87.0, so entries for work that shipped months ago still sit under "Unreleased" (PM2 removal in 0.88.2, cache pre-warm gate and workspace naming in 0.89.0, …). `docs/docs.json` has no versioning either, so there is one live page for every self-hoster whatever version they run, published on merge rather than on release — the version heading is the *only* thing telling a reader whether a change is already in their build. So before adding an entry, run `git tag --contains <commit>` on the change it describes and file it under the release that actually shipped it; only genuinely unshipped work belongs under "Unreleased". What points self-hosters at the page in the first place is `release-drafter.yml`, which appends a "review the Breaking Changes page" line to every release body and groups `⛓️‍💥 breaking-change` PRs under their own heading — which also means a docs-only PR back-documenting an old change shows up in the *next* release's breaking-change list.
- **Greptile enforces the file-order rule on *private* constants too, which CLAUDE.md only states for exported ones.** CLAUDE.md says "Exported types and constants must be placed at the end of the file" and gives the order as imports → exports → helpers → types; Greptile reads that as covering module-private constants as well, and flags a `const` sitting above the file's exported symbol (P2 on [#15226](https://github.com/activepieces/activepieces/pull/15226), for two constants only read inside the service they sat above). It has that as a stored custom-context memory, so it will keep raising it. Put private constants in the helpers section below the export — hoisting is a non-issue when they are only read at call time.
- **`turbo run lint --filter=<pkg>` never typechecks that package, so "0 errors" is no proof it compiles — run `turbo run build --filter=<pkg>` as well.** A package's `lint` script is `eslint 'src/**/*.ts'` with no `tsc`, and the turbo `lint` task's `dependsOn: ["^build"]` builds the package's *upstream dependencies* only, never itself — the `^` is the whole story. So a type error in the package you are editing is invisible to a filtered lint run. CI still catches it, but confusingly under the **lint** job as well as **main**, because linting the whole repo makes your package an upstream of something else whose `^build` finally compiles it. A branch can therefore sit red on two jobs for one `tsc` error that a local filtered lint reported clean.
diff --git a/brain/knowledge/platform-editions-ee/ee-projects-rbac.md b/brain/knowledge/platform-editions-ee/ee-projects-rbac.md
index 7b2baf929c4..a693d30db66 100644
--- a/brain/knowledge/platform-editions-ee/ee-projects-rbac.md
+++ b/brain/knowledge/platform-editions-ee/ee-projects-rbac.md
@@ -25,6 +25,7 @@ Note it lives under `ee/authentication/`, not `ee/projects/`, which is where mos
### Gotchas
- **`rbacMiddleware` only covers HTTP routes. Websocket events bypass it.** A socket is authorized once at connect, against the project it claims in the handshake. After that, every resource id arriving in an event payload is just whatever the client typed, and nothing re-checks it. So a socket handler must look the resource up scoped to the connection's project and check the permission itself. Getting this wrong is how `LOCK_RESOURCE` and `JOIN_PRESENCE` shipped letting any member lock, and read the editors of, another project's flows and tables (SRE-218). `collaborative-resource.ts` has the shape to copy.
- **A new `Permission` needs a row in the role dialog, or custom roles can never grant it.** The toggle list is a hardcoded array, `initialPermissions` in `packages/web/src/app/routes/platform/security/project-role/project-role-dialog.tsx`, and the dialog is a plain `.map()` over it. Default-role grants are hardcoded separately in `access-control-list.ts`, so a permission added there but not here is invisible: ADMIN/EDITOR/VIEWER have it, custom roles cannot be given it, and the feature's tab just never appears for those members. This has already shipped twice — Variables + Knowledge Base (GIT-1751), then Agents. Nothing catches the drift: CI neither typechecks nor unit-tests `web`, so add the row in the same PR as the enum entry.
+- **The release diff and the release apply have to share one rule, or a field becomes either invisible or permanently dirty.** `flowDiffService` decides whether a flow changed by comparing a `normalize()`d copy of each side, and `projectStateHelper.updateFlowInProject` decides what actually gets written — two places, and for connection auth they disagreed both ways. `normalize()` blanked `input.auth` before comparing, so re-pointing a step at a different connection and changing nothing else was reported `flowsUnchanged` and never applied, while the connection the release created sat unreferenced at status `MISSING`; and when some other edit did make the diff fire, the apply unconditionally restored the destination's old auth on top of the incoming one (`f196530db6`, Jul 2024 secret preservation that predates externalId placeholders). Patching the two sites separately is the trap: it leaves a destination-has-auth / incoming-has-none step reporting changed on **every** apply forever, because the diff and the apply then hold different ideas of what unchanged means. The fix (GIT-1764) is one exported `mergeDestinationAuth` that both call, so the diff compares the merged incoming version — exactly what apply is about to write. Any future field with "keep the destination's value" semantics wants the same shape. Worth knowing while reading this code: `flowStructureUtil.transferFlow` deep-clones before the callback runs, so mutating `step` inside it never touches the caller's state; connection references persist as the literal `{{connections['<externalId>']}}`, identical in both projects, which is why comparing them across instances is meaningful at all; and `flowVersionService` recomputes `connectionIds` via `extractConnectionIds` on every mutation, so the version tracks the new reference without anyone updating it by hand.
- **Piece filtering** now via **piece sets** — `project.pieceSetId` (nullable FK, SET NULL). When `managePiecesEnabled`, new EE projects get the Default set on create; unassigned resolves to Default at filter time. This supersedes the legacy project-plan allow/block list.
- **Worker routing**: `workerGroupId` (bare label, `^[a-z0-9_-]+$`) gated by `workerGroupsEnabled`. When set, the project's `EXECUTE_FLOW`/`EXECUTE_WEBHOOK` jobs route to `project-<label>-jobs`; other job types unaffected. Set via `POST /v1/projects/:id`; `GET /v1/projects/worker-groups` (platform-admin) lists online project-scope workers, 402 when flag off.
- `platformProjectService.getForPlatform()`: admins see all, operators see all except others' personal, users see own personal + team projects they're a member of.
diff --git a/docs/install/reference/breaking-changes.mdx b/docs/install/reference/breaking-changes.mdx
index d230c1c3e43..599c198639f 100644
--- a/docs/install/reference/breaking-changes.mdx
+++ b/docs/install/reference/breaking-changes.mdx
@@ -54,6 +54,19 @@ The limit is per file, not per step, so several large files in one step are fine
Nothing unless an AI step handles files larger than 25 MB. Those steps now fail with a size error naming the limit. Raise `AP_MAX_FILE_SIZE_MB` on a self-hosted installation if you need more.
+#### Applying a release or a project replace now updates changed connection references
+
+Applying a release (Environments / Git Sync) or running Project Replace used to keep whatever connection the destination step already pointed at. A step whose connection changed in the source silently kept the old one, and the connection the release created for it stayed unreferenced with status `MISSING`. Two things change:
+
+- A changed connection reference is now a change the diff sees, so a flow whose only edit is its connection is applied instead of being reported as unchanged.
+- The destination's connection is kept only when the incoming step carries no connection of its own, and only when the step is still the same piece. Swapping a step to a different piece no longer grafts the old piece's connection onto it.
+
+Connection secrets still never cross instances. Only the reference travels, and a reference to a connection that does not exist in the destination yet lands as a `MISSING` connection for someone to authorize there.
+
+#### What you need to do
+
+Nothing on upgrade if your source project is the source of truth for connections, which is the intended model. If instead you deliberately re-point a step in the destination project at a different connection than the source uses, that re-point is now overwritten on the next apply. Either point the source at the connection you want, or clear the connection on the source step so the destination wiring is preserved.
+
## 0.91.0
### What has changed?
diff --git a/packages/server/api/src/app/ee/projects/project-release/project-state/diff/flow-diff.service.ts b/packages/server/api/src/app/ee/projects/project-release/project-state/diff/flow-diff.service.ts
index af948459134..e683c33b884 100644
--- a/packages/server/api/src/app/ee/projects/project-release/project-state/diff/flow-diff.service.ts
+++ b/packages/server/api/src/app/ee/projects/project-release/project-state/diff/flow-diff.service.ts
@@ -1,6 +1,7 @@
import { assertNotNullOrUndefined, isNil, mapsAreSame } from '@activepieces/core-utils'
import { DEFAULT_SAMPLE_DATA_SETTINGS, FlowActionType, flowPieceUtil, FlowProjectOperationType, FlowState, flowStructureUtil, FlowTriggerType, FlowVersion, ProjectOperation, ProjectState, Step } from '@activepieces/shared'
import deepEqual from 'deep-equal'
+import { mergeDestinationAuth } from '../project-state-helper'
export const flowDiffService = {
async diff({ newState, currentState }: DiffParams): Promise<ProjectOperation[]> {
@@ -99,7 +100,7 @@ async function isFlowChanged(fromFlow: FlowState, targetFlow: FlowState): Promis
})
const normalizedFromFlow = await normalize(fromFlow.version)
- const normalizedTargetFlow = await normalize(targetFlow.version)
+ const normalizedTargetFlow = await normalize(mergeDestinationAuth({ destinationVersion: fromFlow.version, incomingVersion: targetFlow.version }))
return normalizedFromFlow.displayName !== normalizedTargetFlow.displayName
|| !deepEqual(normalizedFromFlow.trigger, normalizedTargetFlow.trigger) || !isMatched || !notesMatched
}
@@ -109,13 +110,9 @@ async function normalize(flowVersion: FlowVersion): Promise<FlowVersion> {
const clonedStep: Step = JSON.parse(JSON.stringify(step))
clonedStep.settings.sampleData = DEFAULT_SAMPLE_DATA_SETTINGS
clonedStep.lastUpdatedDate = ''
- const authExists = clonedStep?.settings?.input?.auth
if ([FlowActionType.PIECE, FlowTriggerType.PIECE].includes(step.type)) {
clonedStep.settings.pieceVersion = ''
- if (authExists) {
- clonedStep.settings.input.auth = ''
- }
}
return clonedStep
})
diff --git a/packages/server/api/src/app/ee/projects/project-release/project-state/project-state-helper.ts b/packages/server/api/src/app/ee/projects/project-release/project-state/project-state-helper.ts
index 6602857dc94..f6810ae0c77 100644
--- a/packages/server/api/src/app/ee/projects/project-release/project-state/project-state-helper.ts
+++ b/packages/server/api/src/app/ee/projects/project-release/project-state/project-state-helper.ts
@@ -1,5 +1,5 @@
-import { ActivepiecesError, isNil } from '@activepieces/core-utils'
-import { FlowOperationType, FlowState, FlowStatus, flowStructureUtil, FlowSyncError, PopulatedFlow } from '@activepieces/shared'
+import { ActivepiecesError, isEmpty, isNil } from '@activepieces/core-utils'
+import { FlowOperationType, FlowState, FlowStatus, flowStructureUtil, FlowSyncError, FlowVersion, PopulatedFlow } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { flowService } from '../../../../flows/flow/flow.service'
import { projectService } from '../../../../project/project-service'
@@ -22,14 +22,7 @@ export const projectStateHelper = (log: FastifyBaseLogger) => ({
): Promise<PopulatedFlow> {
const project = await projectService(log).getOneOrThrow(projectId)
- const newFlowVersion = flowStructureUtil.transferFlow(newFlow.version, (step) => {
- const oldStep = flowStructureUtil.getStep(step.name, originalFlow.version.trigger)
- const isNotEmptyTrigger = !isNil(step.settings?.input)
- if (oldStep?.settings?.input?.auth && isNotEmptyTrigger) {
- step.settings.input.auth = oldStep.settings.input.auth
- }
- return step
- })
+ const newFlowVersion = mergeDestinationAuth({ destinationVersion: originalFlow.version, incomingVersion: newFlow.version })
const updatedFlow = await flowService(log).update({
id: originalFlow.id,
projectId,
@@ -112,6 +105,24 @@ export const projectStateHelper = (log: FastifyBaseLogger) => ({
},
})
+export function mergeDestinationAuth({ destinationVersion, incomingVersion }: MergeDestinationAuthParams): FlowVersion {
+ return flowStructureUtil.transferFlow(incomingVersion, (step) => {
+ const destinationStep = flowStructureUtil.getStep(step.name, destinationVersion.trigger)
+ const destinationAuth = destinationStep?.settings?.input?.auth
+ const samePiece = destinationStep?.settings?.pieceName === step.settings?.pieceName
+ const incomingInput = step.settings?.input
+ if (!isEmpty(destinationAuth) && samePiece && !isNil(incomingInput) && isEmpty(incomingInput.auth)) {
+ incomingInput.auth = destinationAuth
+ }
+ return step
+ })
+}
+
+type MergeDestinationAuthParams = {
+ destinationVersion: FlowVersion
+ incomingVersion: FlowVersion
+}
+
type RepublishFlowParams = {
flow: PopulatedFlow
projectId: string
diff --git a/packages/server/api/test/integration/cloud/project-replace/release-apply-connection-refs.test.ts b/packages/server/api/test/integration/cloud/project-replace/release-apply-connection-refs.test.ts
new file mode 100644
index 00000000000..e642adb1576
--- /dev/null
+++ b/packages/server/api/test/integration/cloud/project-replace/release-apply-connection-refs.test.ts
@@ -0,0 +1,326 @@
+import {
+ AppConnectionStatus,
+ FlowState,
+ FlowStatus,
+ FlowTrigger,
+ PopulatedFlow,
+ PROJECT_REPLACE_SCHEMA_VERSION,
+ ProjectReplaceRequest,
+} from '@activepieces/shared'
+import { FastifyInstance } from 'fastify'
+import { StatusCodes } from 'http-status-codes'
+import { databaseConnection } from '../../../../src/app/database/database-connection'
+import { db } from '../../../helpers/db'
+import { flowGenerator } from '../../../helpers/flow-generator'
+import {
+ createMockApiKey,
+ mockAndSaveBasicSetup,
+} from '../../../helpers/mocks'
+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
+
+let app: FastifyInstance | null = null
+
+beforeAll(async () => {
+ app = await setupTestEnvironment()
+})
+
+afterAll(async () => {
+ await teardownTestEnvironment()
+})
+
+const OLD_CONN = 'conn_old'
+const NEW_CONN = 'conn_new'
+const DISCORD_CONN = 'conn_discord'
+
+function connRef(externalId: string): string {
+ return `{{connections['${externalId}']}}`
+}
+
+function buildBaseFlow({ projectId, externalId }: { projectId: string, externalId: string }): FlowState {
+ const flow = flowGenerator.simpleActionAndTrigger(externalId)
+ flow.projectId = projectId
+ flow.status = FlowStatus.DISABLED
+ flow.version.displayName = 'connection reference flow'
+ flow.version.trigger.name = 'trigger'
+ flow.version.trigger.nextAction = undefined
+ flow.version.trigger.settings.pieceName = '@activepieces/piece-slack'
+ flow.version.trigger.settings.pieceVersion = '1.0.0'
+ return flow as FlowState
+}
+
+function cloneWith(base: FlowState, mutate: (flow: FlowState) => void): FlowState {
+ const clone = JSON.parse(JSON.stringify(base)) as FlowState
+ mutate(clone)
+ return clone
+}
+
+function replaceBody(overrides: Partial<ProjectReplaceRequest>): ProjectReplaceRequest {
+ return {
+ schemaVersion: PROJECT_REPLACE_SCHEMA_VERSION,
+ sourceActivepiecesVersion: '0.0.1',
+ flows: [],
+ tables: [],
+ folders: [],
+ connections: [
+ { externalId: OLD_CONN, pieceName: '@activepieces/piece-slack', displayName: 'Old Conn' },
+ { externalId: NEW_CONN, pieceName: '@activepieces/piece-slack', displayName: 'New Conn' },
+ ],
+ requiredPieces: [],
+ ...overrides,
+ }
+}
+
+async function setupCtx(): Promise<{ projectId: string, platformId: string, apiKey: string }> {
+ const setup = await mockAndSaveBasicSetup({
+ plan: { environmentsEnabled: true },
+ project: { releasesEnabled: true },
+ })
+ const apiKey = createMockApiKey({ platformId: setup.mockPlatform.id })
+ await db.save('api_key', apiKey)
+ return { projectId: setup.mockProject.id, platformId: setup.mockPlatform.id, apiKey: apiKey.value }
+}
+
+async function postReplace(params: { projectId: string, apiKey: string, body: ProjectReplaceRequest }) {
+ return app!.inject({
+ method: 'POST',
+ url: `/api/v1/projects/${params.projectId}/replace`,
+ headers: { authorization: `Bearer ${params.apiKey}` },
+ body: params.body,
+ })
+}
+
+async function persistedTrigger(params: { projectId: string, externalId: string }): Promise<FlowTrigger> {
+ const flow = await db.findOneByOrFail<PopulatedFlow>('flow', {
+ projectId: params.projectId,
+ externalId: params.externalId,
+ })
+ const versions = await databaseConnection().getRepository('flow_version').find({
+ where: { flowId: flow.id },
+ order: { created: 'DESC' },
+ })
+ expect(versions.length).toBeGreaterThan(0)
+ return versions[0].trigger as FlowTrigger
+}
+
+async function persistedTriggerAuth(params: { projectId: string, externalId: string }): Promise<string | undefined> {
+ const trigger = await persistedTrigger(params)
+ return trigger.settings?.input?.auth as string | undefined
+}
+
+async function seedFlowWithOldConnection(params: { projectId: string, apiKey: string, base: FlowState }): Promise<void> {
+ const response = await postReplace({
+ projectId: params.projectId,
+ apiKey: params.apiKey,
+ body: replaceBody({
+ flows: [cloneWith(params.base, (f) => {
+ f.version.trigger.settings.input = { auth: connRef(OLD_CONN) }
+ })],
+ }),
+ })
+ expect(response.statusCode).toBe(StatusCodes.OK)
+ expect(response.json().applied.flowsCreated).toBe(1)
+}
+
+describe('Release apply / project-replace applies changed connection references (GIT-1764)', () => {
+ it('a connection reference change on its own is seen by the diff and applied', async () => {
+ const { projectId, platformId, apiKey } = await setupCtx()
+ const base = buildBaseFlow({ projectId, externalId: 'flow_auth_only' })
+ await seedFlowWithOldConnection({ projectId, apiKey, base })
+
+ const second = await postReplace({
+ projectId,
+ apiKey,
+ body: replaceBody({
+ flows: [cloneWith(base, (f) => {
+ f.version.trigger.settings.input = { auth: connRef(NEW_CONN) }
+ })],
+ }),
+ })
+ expect(second.statusCode).toBe(StatusCodes.OK)
+ expect(second.json().applied.flowsUpdated).toBe(1)
+ expect(second.json().applied.flowsUnchanged).toBe(0)
+
+ const auth = await persistedTriggerAuth({ projectId, externalId: 'flow_auth_only' })
+ expect(auth).toBe(connRef(NEW_CONN))
+
+ const placeholder = await db.findOneByOrFail<{ status: string }>('app_connection', {
+ platformId,
+ externalId: NEW_CONN,
+ })
+ expect(placeholder.status).toBe(AppConnectionStatus.MISSING)
+ })
+
+ it('a connection reference change alongside another edit is not reverted by the update path', async () => {
+ const { projectId, apiKey } = await setupCtx()
+ const base = buildBaseFlow({ projectId, externalId: 'flow_auth_plus_rename' })
+ await seedFlowWithOldConnection({ projectId, apiKey, base })
+
+ const second = await postReplace({
+ projectId,
+ apiKey,
+ body: replaceBody({
+ flows: [cloneWith(base, (f) => {
+ f.version.displayName = 'connection reference flow renamed'
+ f.version.trigger.settings.input = { auth: connRef(NEW_CONN) }
+ })],
+ }),
+ })
+ expect(second.statusCode).toBe(StatusCodes.OK)
+ expect(second.json().applied.flowsUpdated).toBe(1)
+
+ const trigger = await persistedTrigger({ projectId, externalId: 'flow_auth_plus_rename' })
+ expect(trigger.settings.input?.auth).toBe(connRef(NEW_CONN))
+ })
+
+ it('swapping a step to a different piece keeps that piece own connection instead of grafting the old one', async () => {
+ const { projectId, apiKey } = await setupCtx()
+ const base = buildBaseFlow({ projectId, externalId: 'flow_piece_swap' })
+ await seedFlowWithOldConnection({ projectId, apiKey, base })
+
+ const second = await postReplace({
+ projectId,
+ apiKey,
+ body: replaceBody({
+ flows: [cloneWith(base, (f) => {
+ f.version.trigger.settings.pieceName = '@activepieces/piece-discord'
+ f.version.trigger.settings.input = { auth: connRef(DISCORD_CONN) }
+ })],
+ connections: [
+ { externalId: OLD_CONN, pieceName: '@activepieces/piece-slack', displayName: 'Old Conn' },
+ { externalId: DISCORD_CONN, pieceName: '@activepieces/piece-discord', displayName: 'Discord Conn' },
+ ],
+ }),
+ })
+ expect(second.statusCode).toBe(StatusCodes.OK)
+ expect(second.json().applied.flowsUpdated).toBe(1)
+
+ const trigger = await persistedTrigger({ projectId, externalId: 'flow_piece_swap' })
+ expect(trigger.settings.pieceName).toBe('@activepieces/piece-discord')
+ expect(trigger.settings.input?.auth).toBe(connRef(DISCORD_CONN))
+ })
+
+ it('swapping a step to a different piece never grafts the old connection when the incoming step has none', async () => {
+ const { projectId, apiKey } = await setupCtx()
+ const base = buildBaseFlow({ projectId, externalId: 'flow_piece_swap_blank' })
+ await seedFlowWithOldConnection({ projectId, apiKey, base })
+
+ const second = await postReplace({
+ projectId,
+ apiKey,
+ body: replaceBody({
+ flows: [cloneWith(base, (f) => {
+ f.version.trigger.settings.pieceName = '@activepieces/piece-discord'
+ f.version.trigger.settings.input = {}
+ })],
+ connections: [
+ { externalId: OLD_CONN, pieceName: '@activepieces/piece-slack', displayName: 'Old Conn' },
+ ],
+ }),
+ })
+ expect(second.statusCode).toBe(StatusCodes.OK)
+ expect(second.json().applied.flowsUpdated).toBe(1)
+
+ const trigger = await persistedTrigger({ projectId, externalId: 'flow_piece_swap_blank' })
+ expect(trigger.settings.pieceName).toBe('@activepieces/piece-discord')
+ expect(trigger.settings.input?.auth).toBeUndefined()
+ })
+
+ it('an incoming step with no connection of its own still keeps the destination wiring', async () => {
+ const { projectId, apiKey } = await setupCtx()
+ const base = buildBaseFlow({ projectId, externalId: 'flow_blank_auth' })
+ await seedFlowWithOldConnection({ projectId, apiKey, base })
+
+ const second = await postReplace({
+ projectId,
+ apiKey,
+ body: replaceBody({
+ flows: [cloneWith(base, (f) => {
+ f.version.displayName = 'blank auth renamed'
+ f.version.trigger.settings.input = {}
+ })],
+ }),
+ })
+ expect(second.statusCode).toBe(StatusCodes.OK)
+ expect(second.json().applied.flowsUpdated).toBe(1)
+
+ const auth = await persistedTriggerAuth({ projectId, externalId: 'flow_blank_auth' })
+ expect(auth).toBe(connRef(OLD_CONN))
+ })
+
+ it('a step whose incoming connection is empty settles after one apply instead of reporting a change forever', async () => {
+ const { projectId, apiKey } = await setupCtx()
+ const base = buildBaseFlow({ projectId, externalId: 'flow_blank_auth_settles' })
+ await seedFlowWithOldConnection({ projectId, apiKey, base })
+
+ const blankAuthState = replaceBody({
+ flows: [cloneWith(base, (f) => {
+ f.version.displayName = 'blank auth renamed'
+ f.version.trigger.settings.input = {}
+ })],
+ })
+
+ const second = await postReplace({ projectId, apiKey, body: blankAuthState })
+ expect(second.json().applied.flowsUpdated).toBe(1)
+
+ const third = await postReplace({ projectId, apiKey, body: blankAuthState })
+ expect(third.statusCode).toBe(StatusCodes.OK)
+ expect(third.json().applied.flowsUpdated).toBe(0)
+ expect(third.json().applied.flowsUnchanged).toBe(1)
+
+ const auth = await persistedTriggerAuth({ projectId, externalId: 'flow_blank_auth_settles' })
+ expect(auth).toBe(connRef(OLD_CONN))
+ })
+
+ it('re-applying the same state twice reports no flow changes', async () => {
+ const { projectId, apiKey } = await setupCtx()
+ const base = buildBaseFlow({ projectId, externalId: 'flow_idempotent' })
+ await seedFlowWithOldConnection({ projectId, apiKey, base })
+
+ const second = await postReplace({
+ projectId,
+ apiKey,
+ body: replaceBody({
+ flows: [cloneWith(base, (f) => {
+ f.version.trigger.settings.input = { auth: connRef(OLD_CONN) }
+ })],
+ }),
+ })
+ expect(second.statusCode).toBe(StatusCodes.OK)
+ expect(second.json().applied.flowsUpdated).toBe(0)
+ expect(second.json().applied.flowsUnchanged).toBe(1)
+
+ const auth = await persistedTriggerAuth({ projectId, externalId: 'flow_idempotent' })
+ expect(auth).toBe(connRef(OLD_CONN))
+ })
+
+ it('reverting a connection reference back to the previous one is applied too', async () => {
+ const { projectId, apiKey } = await setupCtx()
+ const base = buildBaseFlow({ projectId, externalId: 'flow_revert' })
+ await seedFlowWithOldConnection({ projectId, apiKey, base })
+
+ const forward = await postReplace({
+ projectId,
+ apiKey,
+ body: replaceBody({
+ flows: [cloneWith(base, (f) => {
+ f.version.trigger.settings.input = { auth: connRef(NEW_CONN) }
+ })],
+ }),
+ })
+ expect(forward.json().applied.flowsUpdated).toBe(1)
+ expect(await persistedTriggerAuth({ projectId, externalId: 'flow_revert' })).toBe(connRef(NEW_CONN))
+
+ const backward = await postReplace({
+ projectId,
+ apiKey,
+ body: replaceBody({
+ flows: [cloneWith(base, (f) => {
+ f.version.trigger.settings.input = { auth: connRef(OLD_CONN) }
+ })],
+ }),
+ })
+ expect(backward.statusCode).toBe(StatusCodes.OK)
+ expect(backward.json().applied.flowsUpdated).toBe(1)
+ expect(await persistedTriggerAuth({ projectId, externalId: 'flow_revert' })).toBe(connRef(OLD_CONN))
+ })
+})