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(connections): replace a connection in chosen flows and fix the project replace (#16874)
Abdul5c66226d6d00
diff --git a/brain/knowledge/flows-execution/flows.md b/brain/knowledge/flows-execution/flows.mdindex 27deae675d0..0c48d4d8fb6 100644--- a/brain/knowledge/flows-execution/flows.md+++ b/brain/knowledge/flows-execution/flows.md@@ -22,6 +22,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.+- **The newest locked version of a flow is not always the live one.** In a project that needs approval to publish, a publish request locks a copy of the draft without making it live, and that copy stays locked after a rejection. Code that wants what is running must load the version the flow points to as published. Loading the newest locked version can pick a pending or rejected request, and publishing it makes changes live that nobody approved. A flow has at most one pending request: a new publish request replaces the pending one, and the replaced copy stays locked with no request pointing to it. So to find what waits for approval, read the pending request, not the newest locked version.- **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.diff --git a/packages/core/shared/src/lib/automation/app-connection/dto/upsert-app-connection-request.ts b/packages/core/shared/src/lib/automation/app-connection/dto/upsert-app-connection-request.tsindex 89fb4f41268..8ef26e51141 100644--- a/packages/core/shared/src/lib/automation/app-connection/dto/upsert-app-connection-request.ts+++ b/packages/core/shared/src/lib/automation/app-connection/dto/upsert-app-connection-request.ts@@ -204,8 +204,8 @@ export const ReplaceAppConnectionsRequestBody = z.object({sourceAppConnectionId: z.string(),targetAppConnectionId: z.string(),projectId: z.string(),- deleteSourceConnection: z.boolean().optional().default(false),applyToPublishedVersions: z.boolean().optional().default(false),+ flowIds: z.array(z.string()).min(1),})export type ReplaceAppConnectionsRequestBody = z.infer<typeof ReplaceAppConnectionsRequestBody>diff --git a/packages/core/shared/src/lib/ee/agent/agent.ts b/packages/core/shared/src/lib/ee/agent/agent.tsindex ccbbc9cfbba..6836eb8cc72 100644--- a/packages/core/shared/src/lib/ee/agent/agent.ts+++ b/packages/core/shared/src/lib/ee/agent/agent.ts@@ -1,6 +1,6 @@import { AgentOutputField, AgentTool } from '@activepieces/core-execution'import { AgentToolType } from '@activepieces/core-piece-types'-import { AIProviderName, ApId, BaseModelSchema, Nullable } from '@activepieces/core-utils'+import { AIProviderName, ApId, BaseModelSchema, Nullable, OptionalArrayFromQuery } from '@activepieces/core-utils'import { z } from 'zod'import { formErrors } from '../../form-errors'import { ColorName } from '../../management/project/project'@@ -143,6 +143,7 @@ const ListAgentsRequest = z.object({sort: z.optional(z.enum(AgentListSort)),cursor: z.string().optional(),limit: z.coerce.number().int().min(1).max(MAX_AGENT_PAGE_SIZE).optional(),+ connectionExternalIds: OptionalArrayFromQuery(z.string()),})const ListAgentRunsRequest = z.object({diff --git a/packages/core/shared/src/lib/ee/audit-events/index.ts b/packages/core/shared/src/lib/ee/audit-events/index.tsindex 2557c23ab40..9c603a588bf 100644--- a/packages/core/shared/src/lib/ee/audit-events/index.ts+++ b/packages/core/shared/src/lib/ee/audit-events/index.ts@@ -388,6 +388,7 @@ export const FlowUpdatedEvent = z.object({updated: true,}),request: FlowOperationRequest,+ reason: z.string().optional(),project: z.object({displayName: z.string(),externalId: Nullable(z.string()),@@ -718,7 +719,8 @@ export type ApplicationEvent = z.infer<typeof ApplicationEvent>export function summarizeApplicationEvent(event: ApplicationEvent) {switch (event.action) {case ApplicationEventName.FLOW_UPDATED: {- return convertUpdateActionToDetails(event)+ const details = convertUpdateActionToDetails(event)+ return `${details}${isNil(event.data.reason) ? '' : ` Reason: ${event.data.reason}`}`}case ApplicationEventName.FLOW_RUN_STARTED:return `Flow run ${event.data.flowRun.id} is started`diff --git a/packages/server/api/src/app/app-connection/app-connection-service/app-connection-service.ts b/packages/server/api/src/app/app-connection/app-connection-service/app-connection-service.tsindex 485e694b694..bb543e4602b 100644--- a/packages/server/api/src/app/app-connection/app-connection-service/app-connection-service.ts+++ b/packages/server/api/src/app/app-connection/app-connection-service/app-connection-service.ts@@ -1,4 +1,4 @@-import { ActivepiecesError, apId, Cursor, ErrorCode, isNil, Metadata, PlatformId, ProjectId, SeekPage, spreadIfDefined, tryCatch, tryCatchSync, unique, UserId } from '@activepieces/core-utils'+import { ActivepiecesError, apId, Cursor, ErrorCode, FlowId, isNil, Metadata, PlatformId, ProjectId, SeekPage, spreadIfDefined, tryCatch, tryCatchSync, unique, UserId } from '@activepieces/core-utils'import { PieceMetadata } from '@activepieces/pieces-framework'import { ApEdition, ApEnvironment, AppConnection, AppConnectionId, AppConnectionOwners, AppConnectionScope, AppConnectionStatus, AppConnectionType, AppConnectionValue, AppConnectionWithoutSensitiveData, ConnectionState, EngineResponse, EngineResponseStatus, ExecuteResolveConnectionIdentifierResponse, ExecuteValidateAuthResponse, MAX_PLATFORM_APP_CONNECTION_OWNERS, OAuth2GrantType, PlatformAppConnectionOwner, PlatformAppConnectionOwnersResponse, PlatformAppConnectionProjectInfo, PlatformAppConnectionsListItem, PlatformRole, UpsertAppConnectionRequestBody, WorkerJobType } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'@@ -264,7 +264,7 @@ export const appConnectionService = (log: FastifyBaseLogger) => ({},async replace(params: ReplaceParams): Promise<void> {- const { sourceAppConnectionId, targetAppConnectionId, projectId, platformId, userId, deleteSourceConnection, applyToPublishedVersions } = params+ const { sourceAppConnectionId, targetAppConnectionId, projectId, platformId, userId, applyToPublishedVersions, flowIds } = paramsif (sourceAppConnectionId === targetAppConnectionId) {throw new ActivepiecesError({code: ErrorCode.VALIDATION,@@ -294,109 +294,31 @@ export const appConnectionService = (log: FastifyBaseLogger) => ({})}- // Mirrors the project-route DELETE guard: platform connections are managed- // from the platform admin page and must not be deletable through a- // project-scoped replace, no matter which projects still use them.- if (deleteSourceConnection && sourceAppConnection.scope === AppConnectionScope.PLATFORM) {- throw new ActivepiecesError({- code: ErrorCode.AUTHORIZATION,- params: {- message: 'Platform connections must be deleted from the platform admin connections page',- },- })- }-- // Reject up-front (before mutating any flow) when published versions this- // replace won't touch still use the source connection. When- // applyToPublishedVersions is set, that is only the published versions- // invisible to the replace (their flow's latest version no longer- // references the connection); updating those in place would overwrite- // the newer draft, so the user has to publish or repoint them first.- // Without it, a delete would orphan every published reference.- const publishedFlowsUsingConnection = deleteSourceConnection || applyToPublishedVersions- ? await appConnectionHandler(log).countPublishedFlowsReferencingConnection({ projectId, externalId: sourceAppConnection.externalId, applyToPublishedVersions })- : 0- if (publishedFlowsUsingConnection > 0) {- throw new ActivepiecesError({- code: ErrorCode.VALIDATION,- params: {- message: deleteSourceConnection- ? 'Cannot delete the old connection because it is still used by published flows that were not updated'- : 'Some published flows still use the old connection but have unpublished draft changes — publish those flows first',- },- })- }-- // Repoint page by page: each repointed flow drops out of the connection- // filter, so re-fetching the first page walks the whole set without the- // cursor skew of paginating rows that are being mutated. The seen-set- // stops the loop if a flow fails to leave the filter (e.g. an auth- // string the rewrite does not understand) instead of spinning forever.- const repointedFlowIds = new Set<string>()- for (;;) {- const flowsPage = await flowService(log).list({- projectIds: [projectId],- cursorRequest: null,- limit: 1000,- folderId: undefined,- name: undefined,- status: undefined,- connectionExternalIds: [sourceAppConnection.externalId],- })- const flowsToRepoint = flowsPage.data.filter((flow) => !repointedFlowIds.has(flow.id))- if (flowsToRepoint.length === 0) {- if (flowsPage.data.length > 0) {- log.warn({ oldConnectionId: sourceAppConnectionId, stuckFlowIds: flowsPage.data.map((flow) => flow.id) }, 'Replace could not rewrite some flow references; they keep the old connection')- }- break- }- await appConnectionHandler(log).updateFlowsWithAppConnection(flowsToRepoint, {- appConnection: sourceAppConnection,- newAppConnection: targetAppConnection,- userId,- applyToPublishedVersions,- })- flowsToRepoint.forEach((flow) => repointedFlowIds.add(flow.id))- }-- log.info({ oldConnectionId: sourceAppConnectionId, newConnectionId: targetAppConnectionId, affectedFlows: repointedFlowIds.size, deleteSourceConnection, applyToPublishedVersions }, 'App connection replaced')-- if (!deleteSourceConnection) {- return- }-- // Final integrity gate before the irreversible delete: a flow whose- // reference could not be rewritten or that was edited or published- // concurrently may still use the connection, and deleting it would- // orphan that flow. The list covers latest-version references; the- // count covers published versions the list cannot see.- const remainingFlows = await flowService(log).list({+ const flows = await flowService(log).list({projectIds: [projectId],cursorRequest: null,- limit: 1,folderId: undefined,name: undefined,status: undefined,- connectionExternalIds: [sourceAppConnection.externalId],+ flowIds,})- const remainingPublishedFlows = remainingFlows.data.length > 0- ? 0- : await appConnectionHandler(log).countPublishedFlowsReferencingConnection({ projectId, externalId: sourceAppConnection.externalId, applyToPublishedVersions: false })- if (remainingFlows.data.length > 0 || remainingPublishedFlows > 0) {+ if (flows.data.length !== unique(flowIds).length) {throw new ActivepiecesError({code: ErrorCode.VALIDATION,params: {- message: 'Cannot delete the old connection because some flows still use it',+ message: `Flows not found in this project: ${unique(flowIds).filter((flowId) => !flows.data.some((flow) => flow.id === flowId)).join(', ')}`,},})}-- await this.delete({- id: sourceAppConnection.id,+ await appConnectionHandler(log).replaceConnectionInFlows({+ flows: flows.data,+ appConnection: sourceAppConnection,+ newAppConnection: targetAppConnection,+ userId,platformId,- scope: sourceAppConnection.scope,- projectId,+ applyToPublishedVersions,})+ log.info({ oldConnectionId: sourceAppConnectionId, newConnectionId: targetAppConnectionId, affectedFlows: flows.data.length, applyToPublishedVersions }, 'App connection replaced')},async delete(params: DeleteParams): Promise<void> {@@ -1059,7 +981,7 @@ type ReplaceParams = {projectId: ProjectIdplatformId: stringuserId: UserId- deleteSourceConnection: booleanapplyToPublishedVersions: boolean+ flowIds: FlowId[]}diff --git a/packages/server/api/src/app/app-connection/app-connection-service/app-connection.handler.ts b/packages/server/api/src/app/app-connection/app-connection-service/app-connection.handler.tsindex d89b3c7ddfa..cb0758667f6 100644--- a/packages/server/api/src/app/app-connection/app-connection-service/app-connection.handler.ts+++ b/packages/server/api/src/app/app-connection/app-connection-service/app-connection.handler.ts@@ -1,6 +1,6 @@-import { ActivepiecesError, assertNotNullOrUndefined, ErrorCode, FlowId, isNil, PlatformId, ProjectId, tryCatch, unique, UserId } from '@activepieces/core-utils'+import { ActivepiecesError, ErrorCode, FlowId, isNil, PlatformId, ProjectId, tryCatch, unique, UserId } from '@activepieces/core-utils'import { PropertyType } from '@activepieces/pieces-framework'-import { AppConnection, AppConnectionStatus, AppConnectionType, AppConnectionValue, AppConnectionWithoutSensitiveData, EngineResponse, EngineResponseStatus, ExecuteRefreshTokenAuthResponse, Flow, FlowOperationType, flowStructureUtil, FlowVersion, FlowVersionState, PopulatedFlow, WorkerJobType } from '@activepieces/shared'+import { AppConnection, AppConnectionStatus, AppConnectionType, AppConnectionValue, AppConnectionWithoutSensitiveData, EngineResponse, EngineResponseStatus, ExecuteRefreshTokenAuthResponse, Flow, FlowOperationType, flowStructureUtil, FlowVersion, PopulatedFlow, WorkerJobType } from '@activepieces/shared'import dayjs from 'dayjs'import { FastifyBaseLogger } from 'fastify'import { lru, LRU } from 'tiny-lru'@@ -11,7 +11,6 @@ import { flowVersionRepo, flowVersionService } from '../../flows/flow-version/flimport { encryptUtils } from '../../helper/encryption'import { exceptionHandler } from '../../helper/exception-handler'import { getPiecePackageWithoutArchive, pieceMetadataService } from '../../pieces/metadata/piece-metadata-service'-import { projectService } from '../../project/project-service'import { userInteractionWatcher } from '../../workers/user-interaction-watcher'import { AppConnectionSchema } from '../app-connection.entity'import { appConnectionsRepo } from './app-connection-service'@@ -19,62 +18,21 @@ import { oauth2Handler } from './oauth2'import { oauth2Util } from './oauth2/oauth2-util'export const appConnectionHandler = (log: FastifyBaseLogger) => ({- async updateFlowsWithAppConnection(flows: PopulatedFlow[], params: UpdateFlowsWithAppConnectionParams): Promise<void> {- const { appConnection, newAppConnection, userId, applyToPublishedVersions } = params+ async replaceConnectionInFlows({ flows, appConnection, newAppConnection, userId, platformId, applyToPublishedVersions }: ReplaceConnectionInFlowsParams): Promise<void> {const flowIdsToRepublish = applyToPublishedVersions? await findFlowIdsToRepublish({ flows, externalId: appConnection.externalId }): new Set<FlowId>()await Promise.all(flows.map(async (flow) => {- const project = await projectService(log).getOneOrThrow(flow.projectId)- const latestVersion = await flowVersionService(log).getFlowVersionOrThrow({- flowId: flow.id,- versionId: undefined,- })- const draftParams = { flow, latestVersion, userId, platformId: project.platformId, appConnection, newAppConnection, log }- if (!flowIdsToRepublish.has(flow.id)) {- await handleDraftVersion(draftParams)+ const replaceParams = { flow, latestVersion: flow.version, userId, platformId, appConnection, newAppConnection, log }+ if (flowIdsToRepublish.has(flow.id)) {+ await replaceConnectionInPublishedAndDraft(replaceParams)return}- const { error } = await tryCatch(() => handleLockedVersion(flow, userId, flow.projectId, project.platformId, appConnection, newAppConnection, log))- const republishedLatestVersion = isNil(error) && !isNil(flow.publishedVersionId) && latestVersion.state === FlowVersionState.LOCKED- if (!republishedLatestVersion) {- await handleDraftVersion(draftParams)- }- if (!isNil(error)) {- throw error- }+ await replaceConnectionInDraft(replaceParams)}))},- // Queries published versions directly rather than relying on the flows fetched- // for the replace, since flowService.list filters by the latest (draft) version's- // connectionIds. A flow whose published version still uses the connection but whose- // newer draft dropped it would be missing from that list, so deleting the source- // would silently orphan the published version.- // When applyToPublishedVersions is set, the replace republishes the published- // versions of the flows it can see (those whose latest version references the- // connection), so only published versions whose flow's latest version dropped the- // connection stay untouched and count as blocking.- async countPublishedFlowsReferencingConnection({ projectId, externalId, applyToPublishedVersions }: CountPublishedFlowsParams): Promise<number> {- const query = flowVersionRepo()- .createQueryBuilder('flow_version')- .innerJoin('flow', 'flow', 'flow.id = flow_version."flowId"')- .where('flow."projectId" = :projectId', { projectId })- .andWhere('flow_version.id = flow."publishedVersionId"')- .andWhere('flow_version."connectionIds" && :externalIds', { externalIds: [externalId] })- if (applyToPublishedVersions) {- const latestVersionConnectionIds = flowVersionRepo()- .createQueryBuilder('fv_latest')- .select('fv_latest."connectionIds"')- .where('fv_latest."flowId" = flow.id')- .orderBy('fv_latest.created', 'DESC')- .limit(1)- query.andWhere(`NOT ((${latestVersionConnectionIds.getQuery()}) && :externalIds)`)- }- return query.getCount()- },-async refresh(connection: AppConnection, projectId: ProjectId, log: FastifyBaseLogger): Promise<AppConnection> {switch (connection.value.type) {case AppConnectionType.PLATFORM_OAUTH2:@@ -362,63 +320,69 @@ async function findFlowIdsToRepublish({ flows, externalId }: FindFlowIdsToRepublreturn new Set()}- const newestLockedConnectionIds = flowVersionRepo()- .createQueryBuilder('fv_locked')- .select('fv_locked."connectionIds"')- .where('fv_locked."flowId" = flow.id')- .andWhere('fv_locked.state = :lockedState')- .orderBy('fv_locked.created', 'DESC')- .limit(1)const rows = await flowVersionRepo().createQueryBuilder('flow_version').select('flow.id', 'flowId').innerJoin('flow', 'flow', 'flow."publishedVersionId" = flow_version.id').where('flow.id IN (:...flowIds)', { flowIds: publishedFlows.map((flow) => flow.id) }).andWhere('flow."projectId" IN (:...projectIds)', { projectIds: unique(publishedFlows.map((flow) => flow.projectId)) })- .andWhere(`(flow_version."connectionIds" && :externalIds OR (${newestLockedConnectionIds.getQuery()}) && :externalIds)`, {- externalIds: [externalId],- lockedState: FlowVersionState.LOCKED,- })+ .andWhere('flow_version."connectionIds" && :externalIds', { externalIds: [externalId] }).getRawMany<{ flowId: FlowId }>()return new Set(rows.map((row) => row.flowId))}-async function handleLockedVersion(flow: PopulatedFlow, userId: UserId, projectId: ProjectId, platformId: PlatformId, appConnection: AppConnectionWithoutSensitiveData, newAppConnection: AppConnectionWithoutSensitiveData, log: FastifyBaseLogger) {- if (isNil(flow.publishedVersionId)) {+async function replaceConnectionInPublishedAndDraft(params: ReplaceConnectionInPublishedAndDraftParams): Promise<void> {+ const { flow, latestVersion, userId, platformId, appConnection, newAppConnection, log } = params+ const projectId = flow.projectId+ const publishedVersionId = flow.publishedVersionId+ if (isNil(publishedVersionId)) {return}- const lastPublishedVersion = await flowVersionService(log).getLatestVersion(flow.id, FlowVersionState.LOCKED)- assertNotNullOrUndefined(lastPublishedVersion, `Last published version not found for flow ${flow.id}`)+ const { error } = await tryCatch(async () => {+ const publishedVersion = await flowVersionService(log).getFlowVersionOrThrow({ flowId: flow.id, versionId: publishedVersionId })- await flowService(log).update({- id: flow.id,- projectId,- platformId,- userId,- previousFlow: flow,- operation: {- type: FlowOperationType.IMPORT_FLOW,- request: replaceConnectionInFlowVersion(lastPublishedVersion, appConnection, newAppConnection),- },- })+ await flowService(log).update({+ id: flow.id,+ projectId,+ platformId,+ userId,+ previousFlow: flow,+ operation: {+ type: FlowOperationType.IMPORT_FLOW,+ request: replaceConnectionInFlowVersion({ flowVersion: publishedVersion, appConnection, newAppConnection }),+ },+ auditExplanation: replaceConnectionAuditExplanation({ appConnection, newAppConnection }),+ })- const { status } = await flowService(log).getOneOrThrow({ id: flow.id, projectId })- await flowService(log).update({- id: flow.id,- projectId,- platformId,- userId,- operation: {- type: FlowOperationType.LOCK_AND_PUBLISH,- request: { status },- },- skipRequiredActionsCheck: true,+ const { status } = await flowService(log).getOneOrThrow({ id: flow.id, projectId })+ await flowService(log).update({+ id: flow.id,+ projectId,+ platformId,+ userId,+ operation: {+ type: FlowOperationType.LOCK_AND_PUBLISH,+ request: { status },+ },+ skipRequiredActionsCheck: true,+ })})++ const hadUnpublishedChanges = latestVersion.id !== publishedVersionId+ const republishFailed = !isNil(error)+ if (hadUnpublishedChanges || republishFailed) {+ await replaceConnectionInDraft({ ...params, restoreDraft: true })+ }+ if (republishFailed) {+ throw error+ }}-async function handleDraftVersion({ flow, latestVersion, userId, platformId, appConnection, newAppConnection, log }: HandleDraftVersionParams): Promise<void> {- if (!latestVersion.connectionIds.includes(appConnection.externalId)) {+async function replaceConnectionInDraft({ flow, latestVersion, userId, platformId, appConnection, newAppConnection, restoreDraft = false, log }: ReplaceConnectionInDraftParams): Promise<void> {+ const usesConnection = latestVersion.connectionIds.includes(appConnection.externalId)+ || flowStructureUtil.extractConnectionIds(latestVersion).includes(appConnection.externalId)+ if (!usesConnection && !restoreDraft) {return}@@ -429,39 +393,36 @@ async function handleDraftVersion({ flow, latestVersion, userId, platformId, appuserId,operation: {type: FlowOperationType.IMPORT_FLOW,- request: replaceConnectionInFlowVersion(latestVersion, appConnection, newAppConnection),+ request: replaceConnectionInFlowVersion({ flowVersion: latestVersion, appConnection, newAppConnection }),},+ auditExplanation: replaceConnectionAuditExplanation({ appConnection, newAppConnection }),})}-function replaceConnectionInFlowVersion(flowVersion: FlowVersion, appConnection: AppConnectionWithoutSensitiveData, newAppConnection: AppConnectionWithoutSensitiveData) {- return flowStructureUtil.transferFlow(flowVersion, (step) => {- if (step.settings?.input?.auth?.includes(appConnection.externalId)) {- return {- ...step,- settings: {- ...step.settings,- input: {- ...step.settings?.input,- auth: replaceConnectionIdInAuth(step.settings.input.auth, appConnection.externalId, newAppConnection.externalId),- },- },- }- }- return step++function replaceConnectionInFlowVersion({ flowVersion, appConnection, newAppConnection }: ReplaceConnectionInFlowVersionParams): FlowVersion {+ return flowStructureUtil.replaceConnection({+ flowVersion,+ sourceExternalId: appConnection.externalId,+ targetExternalId: newAppConnection.externalId,})}-function replaceConnectionIdInAuth(auth: string, oldConnectionId: string, newConnectionId: string): string {- return auth.replace(- new RegExp(`connections\\['${oldConnectionId}'\\]`, 'g'),- `connections['${newConnectionId}']`,- )+function replaceConnectionAuditExplanation({ appConnection, newAppConnection }: Omit<ReplaceConnectionInFlowVersionParams, 'flowVersion'>): string {+ return `replaced connection "${appConnection.displayName}" with "${newAppConnection.displayName}".`+}++type ReplaceConnectionInFlowVersionParams = {+ flowVersion: FlowVersion+ appConnection: AppConnectionWithoutSensitiveData+ newAppConnection: AppConnectionWithoutSensitiveData}-type UpdateFlowsWithAppConnectionParams = {+type ReplaceConnectionInFlowsParams = {+ flows: PopulatedFlow[]appConnection: AppConnectionWithoutSensitiveDatanewAppConnection: AppConnectionWithoutSensitiveDatauserId: UserId+ platformId: PlatformIdapplyToPublishedVersions: boolean}@@ -470,18 +431,17 @@ type FindFlowIdsToRepublishParams = {externalId: string}-type HandleDraftVersionParams = {+type ReplaceConnectionInDraftParams = {flow: FlowlatestVersion: FlowVersionuserId: UserIdplatformId: PlatformIdappConnection: AppConnectionWithoutSensitiveDatanewAppConnection: AppConnectionWithoutSensitiveData+ restoreDraft?: booleanlog: FastifyBaseLogger}-type CountPublishedFlowsParams = {- projectId: ProjectId- externalId: string- applyToPublishedVersions: boolean+type ReplaceConnectionInPublishedAndDraftParams = ReplaceConnectionInDraftParams & {+ flow: PopulatedFlow}diff --git a/packages/server/api/src/app/app-connection/app-connection.controller.ts b/packages/server/api/src/app/app-connection/app-connection.controller.tsindex 32d4c0e69be..a99076809cd 100644--- a/packages/server/api/src/app/app-connection/app-connection.controller.ts+++ b/packages/server/api/src/app/app-connection/app-connection.controller.ts@@ -126,15 +126,11 @@ export const appConnectionController: FastifyPluginCallbackZod = (app, _opts, do)app.post('/replace', ReplaceAppConnectionsRequest, async (request, reply) => {- const { sourceAppConnectionId, targetAppConnectionId, deleteSourceConnection, applyToPublishedVersions } = request.bodyawait appConnectionService(request.log).replace({- sourceAppConnectionId,- targetAppConnectionId,+ ...request.body,projectId: request.projectId,platformId: request.principal.platform.id,userId: request.principal.id,- deleteSourceConnection,- applyToPublishedVersions,})await reply.status(StatusCodes.NO_CONTENT).send()})diff --git a/packages/server/api/src/app/ee/agent/agent-controller.ts b/packages/server/api/src/app/ee/agent/agent-controller.tsindex 8093a5c9250..0a75f9cdf1e 100644--- a/packages/server/api/src/app/ee/agent/agent-controller.ts+++ b/packages/server/api/src/app/ee/agent/agent-controller.ts@@ -36,6 +36,7 @@ export const agentController: FastifyPluginAsyncZod = async (app) => {sort: request.query.sort,cursor: request.query.cursor,limit: request.query.limit,+ connectionExternalIds: request.query.connectionExternalIds,})})diff --git a/packages/server/api/src/app/ee/agent/agent-service.ts b/packages/server/api/src/app/ee/agent/agent-service.tsindex e7c63e5522d..f62aa92b6c8 100644--- a/packages/server/api/src/app/ee/agent/agent-service.ts+++ b/packages/server/api/src/app/ee/agent/agent-service.ts@@ -59,7 +59,7 @@ export const agentService = (log: FastifyBaseLogger) => ({})},- async list({ platformId, userId, projectId, search, sort, cursor, limit }: ListParams): Promise<SeekPage<AgentSummary>> {+ async list({ platformId, userId, projectId, search, sort, cursor, limit, connectionExternalIds }: ListParams): Promise<SeekPage<AgentSummary>> {const readableProjects = await resolveReadableProjects({ platformId, userId, projectId, log })const readableProjectIds = readableProjects.map((project) => project.id)if (readableProjectIds.length === 0) {@@ -86,6 +86,13 @@ export const agentService = (log: FastifyBaseLogger) => ({.orWhere('LOWER(COALESCE(agent."description", \'\')) LIKE :needle', { needle: `%${needle}%` })}))}+ if (!isNil(connectionExternalIds) && connectionExternalIds.length > 0) {+ const connectionAuths = connectionExternalIds.flatMap((externalId) => [externalId, connectionTemplate.wrapExternalId(externalId) ?? externalId])+ query.andWhere(`EXISTS (+ SELECT 1 FROM jsonb_array_elements((agent."draft"->'tools') || COALESCE(agent."published"->'tools', '[]'::jsonb)) AS tool+ WHERE tool->'pieceMetadata'->'predefinedInput'->>'auth' = ANY(:connectionAuths)+ )`, { connectionAuths })+ }const { data, cursor: newCursor } = await paginator.paginate(query)return paginationHelper.createPage(data.map((agent) => toSummary(agent, projectById.get(agent.projectId))), newCursor)@@ -748,6 +755,7 @@ type ListParams = {sort?: AgentListSortcursor?: Cursorlimit?: number+ connectionExternalIds?: string[]}type MoveParams = {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 ba75759767c..58a9fc653c8 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@@ -72,7 +72,7 @@ export const flowSideEffects = (log: FastifyBaseLogger) => ({})},- onOperationApplied({ flow, previousVersion, previousStatus, operation, ...meta }: OnOperationAppliedParams): void {+ onOperationApplied({ flow, previousVersion, previousStatus, operation, auditExplanation, ...meta }: OnOperationAppliedParams): void {applicationEvents(log).sendUserEvent(meta, {action: ApplicationEventName.FLOW_UPDATED,data: {@@ -83,6 +83,7 @@ export const flowSideEffects = (log: FastifyBaseLogger) => ({updated: flow.updated,},request: operation,+ reason: auditExplanation,flowVersion: previousVersion,},})@@ -162,6 +163,7 @@ type OnOperationAppliedParams = FlowEventParams & {previousVersion: FlowVersionpreviousStatus: FlowStatusoperation: FlowOperationRequest+ auditExplanation?: string}type OnDraftWrittenParams = {diff --git a/packages/server/api/src/app/flows/flow/flow.service.ts b/packages/server/api/src/app/flows/flow/flow.service.tsindex 1605086b1c2..10e45396a93 100644--- a/packages/server/api/src/app/flows/flow/flow.service.ts+++ b/packages/server/api/src/app/flows/flow/flow.service.ts@@ -111,6 +111,7 @@ export const flowService = (log: FastifyBaseLogger) => ({connectionExternalIds,agentExternalIds,externalIds,+ flowIds,versionState = FlowVersionState.DRAFT,includeTriggerSource = true,sortBy,@@ -201,6 +202,10 @@ export const flowService = (log: FastifyBaseLogger) => ({queryBuilder.andWhere('ff."externalId" IN (:...externalIds)', { externalIds })}+ if (flowIds !== undefined) {+ queryBuilder.andWhere('ff.id IN (:...flowIds)', { flowIds })+ }+if (connectionExternalIds !== undefined) {const filteredVersion = versionState === FlowVersionState.DRAFT ? 'latest_version' : 'published_version'queryBuilder.andWhere(`${filteredVersion}."connectionIds" && :connectionExternalIds`, { connectionExternalIds })@@ -343,6 +348,7 @@ export const flowService = (log: FastifyBaseLogger) => ({emitEvents = true,skipRequiredActionsCheck = false,editorSessionId = null,+ auditExplanation,}: UpdateParams): Promise<PopulatedFlow> {const flowBeforeOperation = emitEvents? previousFlow ?? await this.getOnePopulatedOrThrow({ id, projectId })@@ -498,6 +504,7 @@ export const flowService = (log: FastifyBaseLogger) => ({previousVersion: flowBeforeOperation.version,previousStatus: flowBeforeOperation.status,operation,+ auditExplanation,})}return updatedFlow@@ -968,6 +975,7 @@ type ListParamsBase = {name?: stringversionState?: FlowVersionStateexternalIds?: string[]+ flowIds?: FlowId[]connectionExternalIds?: string[]agentExternalIds?: string[]includeTriggerSource?: boolean@@ -1015,6 +1023,7 @@ type UpdateParams = EventEmissionParams & {previousFlow?: PopulatedFlowskipRequiredActionsCheck?: booleaneditorSessionId?: string | null+ auditExplanation?: string}type UpdatePublishedVersionIdParams = {diff --git a/packages/server/api/test/integration/ce/app-connection/app-connection-replace.test.ts b/packages/server/api/test/integration/ce/app-connection/app-connection-replace.test.tsindex 0f832321f65..6d9ad5b829d 100644--- a/packages/server/api/test/integration/ce/app-connection/app-connection-replace.test.ts+++ b/packages/server/api/test/integration/ce/app-connection/app-connection-replace.test.ts@@ -3,6 +3,7 @@ import { AppConnection, AppConnectionScope, Flow, FlowStatus, FlowTrigger, FlowTimport dayjs from 'dayjs'import { FastifyInstance } from 'fastify'import { StatusCodes } from 'http-status-codes'+import { In } from 'typeorm'import { databaseConnection } from '../../../../src/app/database/database-connection'import { db } from '../../../helpers/db'import {@@ -27,59 +28,6 @@ const PIECE_NAME = '@activepieces/piece-slack'const MISSING_PIECE_NAME = '@activepieces/piece-does-not-exist'describe('POST /v1/app-connections/replace', () => {- it('keeps the source connection when deleteSourceConnection is not set', async () => {- const ctx = await createTestContext(app!)-- const source = createMockConnection({- platformId: ctx.platform.id,- projectIds: [ctx.project.id],- pieceName: PIECE_NAME,- }, ctx.user.id)- const target = createMockConnection({- platformId: ctx.platform.id,- projectIds: [ctx.project.id],- pieceName: PIECE_NAME,- }, ctx.user.id)- await db.save('app_connection', [source, target])-- const response = await ctx.post('/v1/app-connections/replace', {- sourceAppConnectionId: source.id,- targetAppConnectionId: target.id,- projectId: ctx.project.id,- })-- expect(response?.statusCode).toBe(StatusCodes.NO_CONTENT)- const stillThere = await db.findOneBy<AppConnection>('app_connection', { id: source.id })- expect(stillThere?.id).toBe(source.id)- })-- it('deletes the source connection when deleteSourceConnection is true', async () => {- const ctx = await createTestContext(app!)-- const source = createMockConnection({- platformId: ctx.platform.id,- projectIds: [ctx.project.id],- pieceName: PIECE_NAME,- }, ctx.user.id)- const target = createMockConnection({- platformId: ctx.platform.id,- projectIds: [ctx.project.id],- pieceName: PIECE_NAME,- }, ctx.user.id)- await db.save('app_connection', [source, target])-- const response = await ctx.post('/v1/app-connections/replace', {- sourceAppConnectionId: source.id,- targetAppConnectionId: target.id,- projectId: ctx.project.id,- deleteSourceConnection: true,- })-- expect(response?.statusCode).toBe(StatusCodes.NO_CONTENT)- const deleted = await db.findOneBy<AppConnection>('app_connection', { id: source.id })- expect(deleted).toBeNull()- })-it('rejects replacing a connection with itself', async () => {const ctx = await createTestContext(app!)@@ -94,7 +42,7 @@ describe('POST /v1/app-connections/replace', () => {sourceAppConnectionId: source.id,targetAppConnectionId: source.id,projectId: ctx.project.id,- deleteSourceConnection: true,+ flowIds: ['unused-flow-id'],})expect(response?.statusCode).toBe(StatusCodes.CONFLICT)@@ -102,37 +50,7 @@ describe('POST /v1/app-connections/replace', () => {expect(stillThere?.id).toBe(source.id)})- it('rejects deleting a platform source from the project replace', async () => {- const ctx = await createTestContext(app!)-- const source: AppConnection = {- ...createMockConnection({- platformId: ctx.platform.id,- projectIds: [ctx.project.id],- pieceName: PIECE_NAME,- }, ctx.user.id),- scope: AppConnectionScope.PLATFORM,- }- const target = createMockConnection({- platformId: ctx.platform.id,- projectIds: [ctx.project.id],- pieceName: PIECE_NAME,- }, ctx.user.id)- await db.save('app_connection', [source, target])-- const response = await ctx.post('/v1/app-connections/replace', {- sourceAppConnectionId: source.id,- targetAppConnectionId: target.id,- projectId: ctx.project.id,- deleteSourceConnection: true,- })-- expect(response?.statusCode).toBe(StatusCodes.FORBIDDEN)- const stillThere = await db.findOneBy<AppConnection>('app_connection', { id: source.id })- expect(stillThere?.id).toBe(source.id)- })-- it('replaces flows off a platform source without deleting it', async () => {+ it('replaces flows off a platform source', async () => {const ctx = await createTestContext(app!)const source: AppConnection = {@@ -166,6 +84,7 @@ describe('POST /v1/app-connections/replace', () => {sourceAppConnectionId: source.id,targetAppConnectionId: target.id,projectId: ctx.project.id,+ flowIds: [flow.id],})expect(response?.statusCode).toBe(StatusCodes.NO_CONTENT)@@ -173,108 +92,10 @@ describe('POST /v1/app-connections/replace', () => {expect(stillThere?.id).toBe(source.id)})- it('repoints draft flows before deleting the source', async () => {+ it('republishes a flow whose published version uses the source but whose draft does not, and keeps the draft edits', async () => {const ctx = await createTestContext(app!)+ const { source, target } = await saveSourceAndTarget(ctx)- const source = createMockConnection({- platformId: ctx.platform.id,- projectIds: [ctx.project.id],- pieceName: PIECE_NAME,- }, ctx.user.id)- const target = createMockConnection({- platformId: ctx.platform.id,- projectIds: [ctx.project.id],- pieceName: PIECE_NAME,- }, ctx.user.id)- await db.save('app_connection', [source, target])-- const flow = createMockFlow({- projectId: ctx.project.id,- status: FlowStatus.DISABLED,- })- await db.save('flow', flow)- const draftVersion = createMockFlowVersion({- flowId: flow.id,- state: FlowVersionState.DRAFT,- connectionIds: [source.externalId],- })- await db.save('flow_version', draftVersion)-- const response = await ctx.post('/v1/app-connections/replace', {- sourceAppConnectionId: source.id,- targetAppConnectionId: target.id,- projectId: ctx.project.id,- deleteSourceConnection: true,- })-- // The delete only goes through after the final integrity gate confirms no- // flow still references the source, so a 204 + deleted source proves the- // draft was actually repointed first.- expect(response?.statusCode).toBe(StatusCodes.NO_CONTENT)- const deleted = await db.findOneBy<AppConnection>('app_connection', { id: source.id })- expect(deleted).toBeNull()- })-- it('blocks deleting the source when published flows are not updated', async () => {- const ctx = await createTestContext(app!)-- const source = createMockConnection({- platformId: ctx.platform.id,- projectIds: [ctx.project.id],- pieceName: PIECE_NAME,- }, ctx.user.id)- const target = createMockConnection({- platformId: ctx.platform.id,- projectIds: [ctx.project.id],- pieceName: PIECE_NAME,- }, ctx.user.id)- await db.save('app_connection', [source, target])-- const flow = createMockFlow({- projectId: ctx.project.id,- status: FlowStatus.DISABLED,- })- await db.save('flow', flow)- const publishedVersion = createMockFlowVersion({- flowId: flow.id,- state: FlowVersionState.LOCKED,- connectionIds: [source.externalId],- })- await db.save('flow_version', publishedVersion)- flow.publishedVersionId = publishedVersion.id- await db.save('flow', flow)-- const response = await ctx.post('/v1/app-connections/replace', {- sourceAppConnectionId: source.id,- targetAppConnectionId: target.id,- projectId: ctx.project.id,- deleteSourceConnection: true,- })-- expect(response?.statusCode).toBe(StatusCodes.CONFLICT)- const stillThere = await db.findOneBy<AppConnection>('app_connection', { id: source.id })- expect(stillThere?.id).toBe(source.id)- })-- it('blocks a draft-and-published replace when a published version it cannot see still references the source', async () => {- const ctx = await createTestContext(app!)-- const source = createMockConnection({- platformId: ctx.platform.id,- projectIds: [ctx.project.id],- pieceName: PIECE_NAME,- }, ctx.user.id)- const target = createMockConnection({- platformId: ctx.platform.id,- projectIds: [ctx.project.id],- pieceName: PIECE_NAME,- }, ctx.user.id)- await db.save('app_connection', [source, target])-- // Published version still uses the source but the newer draft dropped it:- // the replace cannot update that published version without overwriting- // the draft, so a draft-and-published replace must refuse instead of- // reporting success while the published flow stays on the old connection.const flow = createMockFlow({projectId: ctx.project.id,status: FlowStatus.DISABLED,@@ -285,14 +106,16 @@ describe('POST /v1/app-connections/replace', () => {state: FlowVersionState.LOCKED,created: '2020-01-01T00:00:00.000Z',connectionIds: [source.externalId],+ trigger: pieceTrigger({ externalId: source.externalId, marker: 'published' }),})- const newerDraftVersion = createMockFlowVersion({+ const draftWithoutSource = createMockFlowVersion({flowId: flow.id,state: FlowVersionState.DRAFT,created: '2020-06-01T00:00:00.000Z',- connectionIds: [],+ connectionIds: [target.externalId],+ trigger: pieceTrigger({ externalId: target.externalId, marker: 'draft-edit' }),})- await db.save('flow_version', [publishedVersion, newerDraftVersion])+ await db.save('flow_version', [publishedVersion, draftWithoutSource])flow.publishedVersionId = publishedVersion.idawait db.save('flow', flow)@@ -300,12 +123,17 @@ describe('POST /v1/app-connections/replace', () => {sourceAppConnectionId: source.id,targetAppConnectionId: target.id,projectId: ctx.project.id,+ flowIds: [flow.id],applyToPublishedVersions: true,})- expect(response?.statusCode).toBe(StatusCodes.CONFLICT)- const stillThere = await db.findOneBy<AppConnection>('app_connection', { id: source.id })- expect(stillThere?.id).toBe(source.id)+ expect(response?.statusCode).toBe(StatusCodes.NO_CONTENT)+ const updatedFlow = await db.findOneByOrFail<Flow>('flow', { id: flow.id })+ const versions = await versionsNewestFirst(flow.id)+ const republished = versions.find((v) => v.id === updatedFlow.publishedVersionId)+ expect(republished?.trigger.settings.input).toEqual({ auth: connectionRef(target.externalId), marker: 'published' })+ expect(versions[0].state).toBe(FlowVersionState.DRAFT)+ expect(versions[0].trigger.settings.input).toEqual({ auth: connectionRef(target.externalId), marker: 'draft-edit' })})it('allows a draft-only replace even when a published version still references the source', async () => {@@ -348,6 +176,7 @@ describe('POST /v1/app-connections/replace', () => {sourceAppConnectionId: source.id,targetAppConnectionId: target.id,projectId: ctx.project.id,+ flowIds: [flow.id],})expect(response?.statusCode).toBe(StatusCodes.NO_CONTENT)@@ -355,58 +184,6 @@ describe('POST /v1/app-connections/replace', () => {expect(stillThere?.id).toBe(source.id)})- it('blocks deleting the source when a published version the replace cannot see still references it', async () => {- const ctx = await createTestContext(app!)-- const source = createMockConnection({- platformId: ctx.platform.id,- projectIds: [ctx.project.id],- pieceName: PIECE_NAME,- }, ctx.user.id)- const target = createMockConnection({- platformId: ctx.platform.id,- projectIds: [ctx.project.id],- pieceName: PIECE_NAME,- }, ctx.user.id)- await db.save('app_connection', [source, target])-- // The published version still uses the source, but the newer draft dropped- // it, so the flow is invisible to the replace's connection filter and its- // published version would be orphaned by the delete.- const flow = createMockFlow({- projectId: ctx.project.id,- status: FlowStatus.DISABLED,- })- await db.save('flow', flow)- const publishedVersion = createMockFlowVersion({- flowId: flow.id,- state: FlowVersionState.LOCKED,- created: '2020-01-01T00:00:00.000Z',- connectionIds: [source.externalId],- })- const newerDraftVersion = createMockFlowVersion({- flowId: flow.id,- state: FlowVersionState.DRAFT,- created: '2020-06-01T00:00:00.000Z',- connectionIds: [],- })- await db.save('flow_version', [publishedVersion, newerDraftVersion])- flow.publishedVersionId = publishedVersion.id- await db.save('flow', flow)-- const response = await ctx.post('/v1/app-connections/replace', {- sourceAppConnectionId: source.id,- targetAppConnectionId: target.id,- projectId: ctx.project.id,- deleteSourceConnection: true,- applyToPublishedVersions: true,- })-- expect(response?.statusCode).toBe(StatusCodes.CONFLICT)- const stillThere = await db.findOneBy<AppConnection>('app_connection', { id: source.id })- expect(stillThere?.id).toBe(source.id)- })-it('keeps unpublished draft edits and a disabled status on a draft-and-published replace', async () => {const ctx = await createTestContext(app!)const { source, target } = await saveSourceAndTarget(ctx)@@ -438,6 +215,7 @@ describe('POST /v1/app-connections/replace', () => {sourceAppConnectionId: source.id,targetAppConnectionId: target.id,projectId: ctx.project.id,+ flowIds: [flow.id],applyToPublishedVersions: true,})@@ -483,6 +261,7 @@ describe('POST /v1/app-connections/replace', () => {sourceAppConnectionId: source.id,targetAppConnectionId: target.id,projectId: ctx.project.id,+ flowIds: [flow.id],applyToPublishedVersions: true,})@@ -515,6 +294,7 @@ describe('POST /v1/app-connections/replace', () => {sourceAppConnectionId: source.id,targetAppConnectionId: target.id,projectId: ctx.project.id,+ flowIds: [flow.id],applyToPublishedVersions: true,})@@ -558,6 +338,7 @@ describe('POST /v1/app-connections/replace', () => {sourceAppConnectionId: source.id,targetAppConnectionId: target.id,projectId: ctx.project.id,+ flowIds: [flow.id],applyToPublishedVersions: true,})@@ -572,6 +353,67 @@ describe('POST /v1/app-connections/replace', () => {expect(versions[0].trigger.settings.input).toEqual({ auth: connectionRef(target.externalId), marker: 'draft-edit' })})+ it('replaces the connection in 200 flows in one request, republishing the published ones', async () => {+ const ctx = await createTestContext(app!)+ const { source, target } = await saveSourceAndTarget(ctx)++ const flows = Array.from({ length: 200 }, () => createMockFlow({ projectId: ctx.project.id, status: FlowStatus.DISABLED }))+ await db.save('flow', flows)+ const publishedFlows = flows.filter((_, index) => index % 2 === 0)+ const liveVersions = publishedFlows.map((flow) => createMockFlowVersion({+ flowId: flow.id,+ state: FlowVersionState.LOCKED,+ created: '2020-01-01T00:00:00.000Z',+ connectionIds: [source.externalId],+ trigger: pieceTrigger({ externalId: source.externalId, marker: 'published' }),+ }))+ const draftVersions = flows.map((flow) => createMockFlowVersion({+ flowId: flow.id,+ state: FlowVersionState.DRAFT,+ created: '2020-06-01T00:00:00.000Z',+ connectionIds: [source.externalId],+ trigger: pieceTrigger({ externalId: source.externalId, marker: 'draft-edit' }),+ }))+ await db.save('flow_version', [...liveVersions, ...draftVersions])+ publishedFlows.forEach((flow, index) => {+ flow.publishedVersionId = liveVersions[index].id+ })+ await db.save('flow', publishedFlows)++ const response = await ctx.post('/v1/app-connections/replace', {+ sourceAppConnectionId: source.id,+ targetAppConnectionId: target.id,+ projectId: ctx.project.id,+ flowIds: flows.map((flow) => flow.id),+ applyToPublishedVersions: true,+ })++ expect(response?.statusCode).toBe(StatusCodes.NO_CONTENT)+ const updatedFlows = await databaseConnection().getRepository<Flow>('flow').find({ where: { id: In(flows.map((flow) => flow.id)) } })+ const versions = await databaseConnection().getRepository<FlowVersion>('flow_version').find({+ where: { flowId: In(flows.map((flow) => flow.id)) },+ order: { created: 'DESC' },+ })+ const newestVersionByFlowId = new Map<string, FlowVersion>()+ versions.forEach((version) => {+ if (!newestVersionByFlowId.has(version.flowId)) {+ newestVersionByFlowId.set(version.flowId, version)+ }+ })+ const versionById = new Map(versions.map((version) => [version.id, version]))+ flows.forEach((flow) => {+ const newestVersion = newestVersionByFlowId.get(flow.id)+ expect(newestVersion?.state).toBe(FlowVersionState.DRAFT)+ expect(newestVersion?.trigger.settings.input).toEqual({ auth: connectionRef(target.externalId), marker: 'draft-edit' })+ })+ const publishedFlowIds = new Set(publishedFlows.map((flow) => flow.id))+ updatedFlows.filter((flow) => publishedFlowIds.has(flow.id)).forEach((flow) => {+ const liveVersion = versionById.get(flow.publishedVersionId ?? '')+ expect(liveVersion?.trigger.settings.input).toEqual({ auth: connectionRef(target.externalId), marker: 'published' })+ })+ expect(updatedFlows.filter((flow) => !publishedFlowIds.has(flow.id)).every((flow) => isNil(flow.publishedVersionId))).toBe(true)+ }, 600_000)+it('decides the republish per flow when one replace covers several flows', async () => {const ctx = await createTestContext(app!)const { source, target } = await saveSourceAndTarget(ctx)@@ -622,6 +464,7 @@ describe('POST /v1/app-connections/replace', () => {sourceAppConnectionId: source.id,targetAppConnectionId: target.id,projectId: ctx.project.id,+ flowIds: [draftOnlyFlow.id, publishedFlow.id],applyToPublishedVersions: true,})@@ -638,7 +481,7 @@ describe('POST /v1/app-connections/replace', () => {expect(publishedFlowVersions[0].trigger.settings.input).toEqual({ auth: connectionRef(target.externalId), marker: 'draft-edit' })})- it('rewires a newer locked version that uses the source connection even when the live version does not', async () => {+ it('republishes the live version, and keeps a newer locked version that is not live in the draft', async () => {const ctx = await createTestContext(app!)const { source, target } = await saveSourceAndTarget(ctx)@@ -651,8 +494,8 @@ describe('POST /v1/app-connections/replace', () => {flowId: flow.id,state: FlowVersionState.LOCKED,created: '2020-01-01T00:00:00.000Z',- connectionIds: [target.externalId],- trigger: pieceTrigger({ externalId: target.externalId, marker: 'published' }),+ connectionIds: [source.externalId],+ trigger: pieceTrigger({ externalId: source.externalId, marker: 'published' }),})const submittedVersion = createMockFlowVersion({flowId: flow.id,@@ -669,13 +512,84 @@ describe('POST /v1/app-connections/replace', () => {sourceAppConnectionId: source.id,targetAppConnectionId: target.id,projectId: ctx.project.id,+ flowIds: [flow.id],applyToPublishedVersions: true,})expect(response?.statusCode).toBe(StatusCodes.NO_CONTENT)const versions = await versionsNewestFirst(flow.id)- const newestLocked = versions.find((v) => v.state === FlowVersionState.LOCKED)- expect(newestLocked?.trigger.settings.input).toEqual({ auth: connectionRef(target.externalId), marker: 'submitted' })+ const updatedFlow = await db.findOneBy<Flow>('flow', { id: flow.id })+ const newLiveVersion = versions.find((v) => v.id === updatedFlow?.publishedVersionId)+ expect(newLiveVersion?.id).not.toBe(liveVersion.id)+ expect(newLiveVersion?.trigger.settings.input).toEqual({ auth: connectionRef(target.externalId), marker: 'published' })+ expect(versions[0].state).toBe(FlowVersionState.DRAFT)+ expect(versions[0].trigger.settings.input).toEqual({ auth: connectionRef(target.externalId), marker: 'submitted' })+ })++ it('repoints only the listed flows, and keeps their sample data', async () => {+ const ctx = await createTestContext(app!)+ const { source, target } = await saveSourceAndTarget(ctx)++ const listedFlow = createMockFlow({ projectId: ctx.project.id, status: FlowStatus.DISABLED })+ const otherFlow = createMockFlow({ projectId: ctx.project.id, status: FlowStatus.DISABLED })+ await db.save('flow', [listedFlow, otherFlow])+ await db.save('flow_version', [+ createMockFlowVersion({+ flowId: listedFlow.id,+ state: FlowVersionState.DRAFT,+ connectionIds: [source.externalId],+ trigger: pieceTrigger({ externalId: source.externalId, marker: 'listed', sampleDataFileId: 'listed-sample' }),+ }),+ createMockFlowVersion({+ flowId: otherFlow.id,+ state: FlowVersionState.DRAFT,+ connectionIds: [source.externalId],+ trigger: pieceTrigger({ externalId: source.externalId, marker: 'other' }),+ }),+ ])++ const response = await ctx.post('/v1/app-connections/replace', {+ flowIds: [listedFlow.id],+ sourceAppConnectionId: source.id,+ targetAppConnectionId: target.id,+ projectId: ctx.project.id,+ })++ expect(response?.statusCode).toBe(StatusCodes.NO_CONTENT)+ const [listedVersion] = await versionsNewestFirst(listedFlow.id)+ expect(listedVersion.trigger.settings.input).toEqual({ auth: connectionRef(target.externalId), marker: 'listed' })+ expect(listedVersion.trigger.settings.sampleData?.sampleDataFileId).toBe('listed-sample')+ const [otherVersion] = await versionsNewestFirst(otherFlow.id)+ expect(otherVersion.trigger.settings.input).toEqual({ auth: connectionRef(source.externalId), marker: 'other' })+ const stillThere = await db.findOneBy<AppConnection>('app_connection', { id: source.id })+ expect(stillThere?.id).toBe(source.id)+ })++ it('rejects a flow from another project', async () => {+ const ctx = await createTestContext(app!)+ const otherCtx = await createTestContext(app!)+ const { source, target } = await saveSourceAndTarget(ctx)++ const foreignFlow = createMockFlow({ projectId: otherCtx.project.id, status: FlowStatus.DISABLED })+ await db.save('flow', foreignFlow)+ await db.save('flow_version', createMockFlowVersion({+ flowId: foreignFlow.id,+ state: FlowVersionState.DRAFT,+ connectionIds: [source.externalId],+ trigger: pieceTrigger({ externalId: source.externalId, marker: 'foreign' }),+ }))++ const response = await ctx.post('/v1/app-connections/replace', {+ flowIds: [foreignFlow.id],+ sourceAppConnectionId: source.id,+ targetAppConnectionId: target.id,+ projectId: ctx.project.id,+ })++ expect(response?.statusCode).toBe(StatusCodes.CONFLICT)+ expect(response?.json().params.message).toContain(foreignFlow.id)+ const [foreignVersion] = await versionsNewestFirst(foreignFlow.id)+ expect(foreignVersion.trigger.settings.input).toEqual({ auth: connectionRef(source.externalId), marker: 'foreign' })})})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.tsindex 2c743ad59dc..e5f18d59482 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@@ -754,6 +754,27 @@ describe('agent list across projects', () => {expect(noMatch).toStrictEqual([])})+ it('lists the agents whose draft or published tools use one of the given connections', async () => {+ const ctx = await context()+ const pieceTool = (auth: string) => ({+ type: 'PIECE',+ toolName: 'create_issue',+ pieceMetadata: {+ pieceName: '@activepieces/piece-github',+ pieceVersion: '0.1.0',+ actionName: 'create_issue',+ predefinedInput: { auth, fields: {} },+ },+ })+ const usesInDraft = await createAgent(ctx, { displayName: 'Draft user', draft: { ...agentBody(ctx.project.id).draft, tools: [pieceTool('{{connections[\'conn-a\']}}')] } })+ const usesInPublished = await createAgent(ctx, { displayName: 'Published user' })+ await db.update('agent', usesInPublished.id, { published: { ...agentBody(ctx.project.id).draft, tools: [pieceTool('conn-b')] } })+ await createAgent(ctx, { displayName: 'Other connection', draft: { ...agentBody(ctx.project.id).draft, tools: [pieceTool('conn-c')] } })++ const listed = (await ctx.get('/v1/agents', { connectionExternalIds: ['conn-a', 'conn-b'] })).json().data+ expect(listed.map((row: { id: string }) => row.id).sort()).toStrictEqual([usesInDraft.id, usesInPublished.id].sort())+ })+it('sorts by name when asked, rather than by when it was touched', async () => {const ctx = await context()const apple = await createAgent(ctx, { displayName: 'Apple duty' })diff --git a/packages/server/api/test/integration/ee/piece-sets/required-actions.test.ts b/packages/server/api/test/integration/ee/piece-sets/required-actions.test.tsindex 1336917b1aa..b168a6e2230 100644--- a/packages/server/api/test/integration/ee/piece-sets/required-actions.test.ts+++ b/packages/server/api/test/integration/ee/piece-sets/required-actions.test.ts@@ -227,6 +227,7 @@ describe('Required actions', () => {targetAppConnectionId: target.id,projectId: ctx.project.id,applyToPublishedVersions: true,+ flowIds: [flow.id],})expect(response.statusCode).toBe(StatusCodes.NO_CONTENT)diff --git a/packages/web/src/app/connections/replace-connections-dialog.tsx b/packages/web/src/app/connections/replace-connections-dialog.tsxindex d738f5886b8..b0aae7bc9c1 100644--- a/packages/web/src/app/connections/replace-connections-dialog.tsx+++ b/packages/web/src/app/connections/replace-connections-dialog.tsx@@ -1,4 +1,3 @@-import { isNil } from '@activepieces/core-utils';import { AppConnectionScope, PopulatedFlow } from '@activepieces/shared';import { useMutation } from '@tanstack/react-query';import { t } from 'i18next';@@ -62,7 +61,6 @@ type FormData = {};type VersionScope = 'draft' | 'published';-type OldConnectionAction = 'keep' | 'delete';enum STEP {SELECT = 'SELECT',@@ -78,8 +76,6 @@ const ReplaceConnectionsDialog = ({const [step, setStep] = useState<STEP>(STEP.SELECT);const [affectedFlows, setAffectedFlows] = useState<Array<PopulatedFlow>>([]);const [versionScope, setVersionScope] = useState<VersionScope>('draft');- const [oldConnectionAction, setOldConnectionAction] =- useState<OldConnectionAction>('keep');const { pieces, isLoading: piecesLoading } = piecesHooks.usePieces({});const { data: connections, isLoading: connectionsLoading } =@@ -185,10 +181,6 @@ const ReplaceConnectionsDialog = ({name: 'sourceConnections.id',});- const sourceIsGlobalConnection =- filteredConnections.find((conn) => conn.id === sourceConnectionId)- ?.scope === AppConnectionScope.PLATFORM;-const replacedWithOptions = useMemo(() => {return filteredConnections.filter((conn) => conn.id !== sourceConnectionId)@@ -198,22 +190,12 @@ const ReplaceConnectionsDialog = ({}));}, [filteredConnections, sourceConnectionId]);- const publishedAffectedCount = affectedFlows.filter(- (flow) => !isNil(flow.publishedVersionId),- ).length;const applyToPublishedVersions = versionScope === 'published';- const deleteBlockedByPublishedFlows =- !applyToPublishedVersions && publishedAffectedCount > 0;- const effectiveDeleteSourceConnection =- oldConnectionAction === 'delete' &&- !deleteBlockedByPublishedFlows &&- !sourceIsGlobalConnection;const handleBack = () => {setStep(STEP.SELECT);setAffectedFlows([]);setVersionScope('draft');- setOldConnectionAction('keep');};const handleConfirmedSubmit = async (values: FormData) => {@@ -228,10 +210,10 @@ const ReplaceConnectionsDialog = ({}replaceConnections({+ flowIds: affectedFlows.map((flow) => flow.id),sourceAppConnectionId: values.sourceConnections.id,targetAppConnectionId: values.replacedWithConnection.id,projectId: projectId,- deleteSourceConnection: effectiveDeleteSourceConnection,applyToPublishedVersions,});};@@ -242,7 +224,6 @@ const ReplaceConnectionsDialog = ({setStep(STEP.SELECT);setAffectedFlows([]);setVersionScope('draft');- setOldConnectionAction('keep');};const navigate = useNavigate();@@ -337,7 +318,6 @@ const ReplaceConnectionsDialog = ({id: '',externalId: '',});- setOldConnectionAction('keep');}}options={filteredConnections.map((conn) => ({label: conn.displayName,@@ -480,13 +460,9 @@ const ReplaceConnectionsDialog = ({/><Selectvalue={versionScope}- onValueChange={(value) => {- const scope = value as VersionScope;- setVersionScope(scope);- if (scope === 'draft' && publishedAffectedCount > 0) {- setOldConnectionAction('keep');- }- }}+ onValueChange={(value) =>+ setVersionScope(value as VersionScope)+ }><SelectTrigger><SelectValue />@@ -500,38 +476,6 @@ const ReplaceConnectionsDialog = ({</Select></div>- <div className="flex flex-col gap-1.5">- <LabelWithTooltip- label={t('After replacing')}- tooltip={t(- 'Keep the old connection to reuse it later, or delete it for good. Deleting is unavailable while published flows still use it — switch the option above to Draft and published first. Global connections can only be deleted from the platform admin page.',- )}- />- <Select- value={oldConnectionAction}- onValueChange={(value) =>- setOldConnectionAction(value as OldConnectionAction)- }- >- <SelectTrigger>- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="keep">- {t('Keep the old connection')}- </SelectItem>- <SelectItem- value="delete"- disabled={- deleteBlockedByPublishedFlows || sourceIsGlobalConnection- }- >- {t('Delete the old connection')}- </SelectItem>- </SelectContent>- </Select>- </div>-<span className="text-xs text-gray-11">{t('MCP servers are not updated automatically — reconnect them manually.',@@ -546,6 +490,7 @@ const ReplaceConnectionsDialog = ({type="button"onClick={() => handleConfirmedSubmit(form.getValues())}loading={isReplacing}+ disabled={affectedFlows.length === 0}>{t('Replace')}</Button>