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(builder): replace connections from a Connections button in the builder header (#17106)
Abdul4f343e12e14c
diff --git a/packages/core/execution/src/lib/flows/util/flow-structure-util.ts b/packages/core/execution/src/lib/flows/util/flow-structure-util.tsindex 009376250cb..96353d4ecec 100644--- a/packages/core/execution/src/lib/flows/util/flow-structure-util.ts+++ b/packages/core/execution/src/lib/flows/util/flow-structure-util.ts@@ -279,11 +279,16 @@ function isAgentPiece(action: Step) {)}-function extractConnectionIds(flowVersion: FlowVersion): string[] {- const stepAuthIds = getAllSteps(flowVersion.trigger).flatMap((step) =>- step.settings?.input?.auth ? extractConnectionIdsFromAuth(step.settings.input.auth) : [],- )- return unique([...stepAuthIds, ...extractAgentToolsConnectionIds(flowVersion)])+function extractFlowConnectionIds(flowVersion: FlowVersion): string[] {+ return unique(getAllSteps(flowVersion.trigger).flatMap(extractStepConnectionIds))+}++function extractStepConnectionIds(step: Step): string[] {+ const stepConnectionExternalIds = step.settings?.input?.auth ? extractConnectionIdsFromAuth(step.settings.input.auth) : []+ const agentToolConnectionExternalIds = getAgentToolsInlinedInStep(step)+ .map(getAgentToolConnectionId)+ .filter((connectionExternalId): connectionExternalId is string => !isNil(connectionExternalId) && connectionExternalId !== '')+ return unique([...stepConnectionExternalIds, ...agentToolConnectionExternalIds])}function getAgentToolConnectionId(tool: unknown): string | undefined {@@ -380,7 +385,8 @@ export const flowStructureUtil = {hasContinueOnFailureBranches,getSkippedStepNames,isSkipped,- extractConnectionIds,+ extractFlowConnectionIds,+ extractStepConnectionIds,isAgentPiece,isBranchedAction,extractAgentIds,diff --git a/packages/core/execution/test/flow/replace-connection.test.ts b/packages/core/execution/test/flow/replace-connection.test.tsindex d91427eaeb5..f702203a1db 100644--- a/packages/core/execution/test/flow/replace-connection.test.ts+++ b/packages/core/execution/test/flow/replace-connection.test.ts@@ -67,7 +67,7 @@ describe('flowStructureUtil.replaceConnection', () => {expect(authOf(result, 'step_2')).toBe("{{connections['other']}}")expect(authOf(result, 'step_3')).toBe("{{connections['new']}}")expect(flowStructureUtil.getStepOrThrow('step_1', result.trigger).settings.input.channel).toBe('general')- expect(flowStructureUtil.extractConnectionIds(result)).toEqual(['new', 'other'])+ expect(flowStructureUtil.extractFlowConnectionIds(result)).toEqual(['new', 'other'])})it('does not change a step whose auth points at a connection that only starts with the source name', () => {@@ -98,7 +98,7 @@ describe('flowStructureUtil.replaceConnection', () => {}const flowVersion = flowWith(agentStep)expect(flowStructureUtil.extractAgentToolsConnectionIds(flowVersion)).toEqual(['old', 'other'])- expect(flowStructureUtil.extractConnectionIds(flowVersion)).toEqual(['old', 'other'])+ expect(flowStructureUtil.extractFlowConnectionIds(flowVersion)).toEqual(['old', 'other'])const result = flowStructureUtil.replaceConnection({ flowVersion, sourceExternalId: 'old', targetExternalId: 'new' })@@ -125,6 +125,31 @@ describe('flowStructureUtil.replaceConnection', () => {})})+describe('flowStructureUtil.extractStepConnectionIds', () => {+ it('returns the connections of one step, from its auth and its agent tools', () => {+ const step = pieceStep({ name: 'step_1', auth: "{{connections['slack']}}" })+ const agentStep: PieceAction = {+ ...pieceStep({ name: 'step_2' }),+ settings: {+ pieceName: '@activepieces/piece-ai',+ pieceVersion: '0.6.0',+ actionName: 'run_agent',+ input: {+ agentTools: [+ slackTool({ toolName: 'send', auth: 'old' }),+ slackTool({ toolName: 'reply', auth: "{{connections['old']}}" }),+ mcpTool,+ ],+ },+ propertySettings: {},+ },+ }+ expect(flowStructureUtil.extractStepConnectionIds(step)).toEqual(['slack'])+ expect(flowStructureUtil.extractStepConnectionIds(agentStep)).toEqual(['old'])+ expect(flowStructureUtil.extractStepConnectionIds(pieceStep({ name: 'step_3' }))).toEqual([])+ })+})+describe('flowStructureUtil.replaceAgentToolConnection', () => {it('points a piece tool that uses the source connection, in plain or wrapped form, at the target connection', () => {const tools = [diff --git a/packages/server/api/src/app/database/migration/postgres/1745530653784-AddConnectionIdsToFlowVersion.ts b/packages/server/api/src/app/database/migration/postgres/1745530653784-AddConnectionIdsToFlowVersion.tsindex 71bbb106924..561008340ba 100644--- a/packages/server/api/src/app/database/migration/postgres/1745530653784-AddConnectionIdsToFlowVersion.ts+++ b/packages/server/api/src/app/database/migration/postgres/1745530653784-AddConnectionIdsToFlowVersion.ts@@ -23,7 +23,7 @@ export class AddConnectionIdsToFlowVersion1745530653784 implements MigrationInte// Update existing rowsconst flowVersions = await queryRunner.query('SELECT * FROM flow_version')for (const flowVersion of flowVersions) {- const connectionIds = flowStructureUtil.extractConnectionIds(flowVersion)+ const connectionIds = flowStructureUtil.extractFlowConnectionIds(flowVersion)await queryRunner.query('UPDATE flow_version SET "connectionIds" = $1 WHERE id = $2', [connectionIds, flowVersion.id])}diff --git a/packages/server/api/src/app/flows/flow-version/flow-version.service.ts b/packages/server/api/src/app/flows/flow-version/flow-version.service.tsindex 64097452170..3c1b90ae3ab 100644--- a/packages/server/api/src/app/flows/flow-version/flow-version.service.ts+++ b/packages/server/api/src/app/flows/flow-version/flow-version.service.ts@@ -123,7 +123,7 @@ export const flowVersionService = (log: FastifyBaseLogger) => ({if (userId) {mutatedFlowVersion.updatedBy = userId}- mutatedFlowVersion.connectionIds = flowStructureUtil.extractConnectionIds(mutatedFlowVersion)+ mutatedFlowVersion.connectionIds = flowStructureUtil.extractFlowConnectionIds(mutatedFlowVersion)mutatedFlowVersion.agentIds = flowStructureUtil.extractAgentIds(mutatedFlowVersion)return flowVersionRepo(entityManager).save(sanitizeObjectForPostgresql(mutatedFlowVersion))},diff --git a/packages/server/api/src/app/flows/flow-version/migrations/migrate-v1-connection-ids.ts b/packages/server/api/src/app/flows/flow-version/migrations/migrate-v1-connection-ids.tsindex fcfc78ae94c..19fa325b11a 100644--- a/packages/server/api/src/app/flows/flow-version/migrations/migrate-v1-connection-ids.ts+++ b/packages/server/api/src/app/flows/flow-version/migrations/migrate-v1-connection-ids.ts@@ -7,7 +7,7 @@ export const migrateConnectionIds: Migration = {return {...flowVersion,schemaVersion: '2',- connectionIds: flowStructureUtil.extractConnectionIds(flowVersion),+ connectionIds: flowStructureUtil.extractFlowConnectionIds(flowVersion),}},}\ No newline at end of filediff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex d9a83cd64fe..45feb032515 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -832,8 +832,6 @@"Choose connection to replace with": "Choose connection to replace with","No flows use this connection yet": "No flows use this connection yet","flowsUsingConnection": "{count, plural, =1 {1 flow uses this connection} other {# flows use this connection}}",- "Switch the steps of this flow from one connection to another. Other flows are not changed.": "Switch the steps of this flow from one connection to another. Other flows are not changed.",- "Steps that use the replaced connection keep their settings. Test your flow to make sure nothing breaks.": "Steps that use the replaced connection keep their settings. Test your flow to make sure nothing breaks.","Which versions to update": "Which versions to update","Draft only updates your working copy. Live flows keep using the old connection until you publish them again. Draft and published republishes affected flows now, which can interrupt running automations.": "Draft only updates your working copy. Live flows keep using the old connection until you publish them again. Draft and published republishes affected flows now, which can interrupt running automations.","Draft only": "Draft only",@@ -3720,5 +3718,11 @@"Ask us to add them to your license, then follow the setup guide to start your first group.": "Ask us to add them to your license, then follow the setup guide to start your first group.","Available on self-hosted Activepieces. Talk to sales to set it up.": "Available on self-hosted Activepieces. Talk to sales to set it up.","A replace changes up to {max} flows.": "A replace changes up to {max} flows.",- "These still use the connection and stop working if you delete it:": "These still use the connection and stop working if you delete it:"+ "These still use the connection and stop working if you delete it:": "These still use the connection and stop working if you delete it:",+ "Connections in this flow": "Connections in this flow",+ "Replacing a connection updates every step that uses it.": "Replacing a connection updates every step that uses it.",+ "usedInStepsCount": "{count, plural, =1 {Used in 1 step} other {Used in # steps}}",+ "Replace {name}": "Replace {name}",+ "Every step in this flow that uses {name} will switch to the connection you pick below.": "Every step in this flow that uses {name} will switch to the connection you pick below.",+ "Test the flow after the replace to make sure every step still works.": "Test the flow after the replace to make sure every step still works."}diff --git a/packages/web/src/app/builder/builder-header/builder-header.tsx b/packages/web/src/app/builder/builder-header/builder-header.tsxindex 2f52fecde49..047bbfb2775 100644--- a/packages/web/src/app/builder/builder-header/builder-header.tsx+++ b/packages/web/src/app/builder/builder-header/builder-header.tsx@@ -2,6 +2,7 @@ import { Permission } from '@activepieces/core-utils';import {ApFlagId,FlowOperationType,+ FlowVersionState,supportUrl,UncategorizedFolderId,} from '@activepieces/shared';@@ -11,6 +12,7 @@ import { ChevronDown, CircleHelp, HistoryIcon } from 'lucide-react';import { useEffect, useState } from 'react';import {createSearchParams,+ useLocation,useNavigate,useSearchParams,} from 'react-router-dom';@@ -45,11 +47,13 @@ import { cn } from '@/lib/utils';import FlowActionMenu from '../../components/flow-actions-menu';import { flowCanvasConsts } from '../flow-canvas/utils/consts';+import { FlowConnectionsPopover } from './flow-connections-popover';import { BuilderFlowStatusSection } from './flow-status';export const BuilderHeader = ({ isFlowLocked }: { isFlowLocked: boolean }) => {const [queryParams] = useSearchParams();const navigate = useNavigate();+ const isRunsPage = useLocation().pathname.includes('/runs');const queryClient = useQueryClient();const openNewWindow = useNewWindow();const { data: showSupport } = flagsHooks.useFlag<boolean>(@@ -84,6 +88,9 @@ export const BuilderHeader = ({ isFlowLocked }: { isFlowLocked: boolean }) => {flow.folderId ?? UncategorizedFolderId,);+ const isLatestVersion =+ flowVersion.state === FlowVersionState.DRAFT ||+ flowVersion.id === flow.publishedVersionId;const [isEditingFlowName, setIsEditingFlowName] = useState(false);useEffect(() => {setIsEditingFlowName(queryParams.get(NEW_FLOW_QUERY_PARAM) === 'true');@@ -150,7 +157,6 @@ export const BuilderHeader = ({ isFlowLocked }: { isFlowLocked: boolean }) => {}}insideBuilder={true}savePendingEdits={savePendingEdits}- isFlowLocked={isFlowLocked}flow={flow}flowVersion={flowVersion}readonly={readonly}@@ -176,6 +182,11 @@ export const BuilderHeader = ({ isFlowLocked }: { isFlowLocked: boolean }) => {const rightContent = (<div className="flex items-center justify-center gap-4">+ {isLatestVersion &&+ !isRunsPage &&+ !embedState.hideConnectionsInBuilder && (+ <FlowConnectionsPopover isFlowLocked={isFlowLocked} />+ )}{showSupport && (<Button variant="ghost" onClick={() => openNewWindow(supportUrl)}><CircleHelp className="w-4 h-4"></CircleHelp>diff --git a/packages/web/src/app/builder/builder-header/flow-connections-popover.tsx b/packages/web/src/app/builder/builder-header/flow-connections-popover.tsxnew file mode 100644index 00000000000..2c574fdc3db--- /dev/null+++ b/packages/web/src/app/builder/builder-header/flow-connections-popover.tsx@@ -0,0 +1,121 @@+import { Permission } from '@activepieces/core-utils';+import { AppConnectionWithoutSensitiveData } from '@activepieces/shared';+import { t } from 'i18next';+import { Plug } from 'lucide-react';+import { useState } from 'react';++import { flowCanvasHooks } from '@/app/builder/flow-canvas/hooks';+import { PermissionNeededTooltip } from '@/components/custom/permission-needed-tooltip';+import { TextWithTooltip } from '@/components/custom/text-with-tooltip';+import { useEmbedding } from '@/components/providers/embed-provider';+import { Button } from '@/components/ui/button';+import {+ Popover,+ PopoverContent,+ PopoverDescription,+ PopoverHeader,+ PopoverTitle,+ PopoverTrigger,+} from '@/components/ui/popover';+import { ScrollArea } from '@/components/ui/scroll-area';+import { PieceIconWithPieceName } from '@/features/pieces';+import { useAuthorization } from '@/hooks/authorization-hooks';++import { ReplaceConnectionForFlowDialog } from './replace-connection-for-flow-dialog';++export const FlowConnectionsPopover = ({+ isFlowLocked,+}: {+ isFlowLocked: boolean;+}) => {+ const { flowConnections } = flowCanvasHooks.useFlowConnections();+ const showReplace = !useEmbedding().embedState.hideReplaceConnection;+ const hasPermissionToReplace = useAuthorization().checkAccess(+ Permission.REPLACE_APP_CONNECTION,+ );+ const [popoverOpen, setPopoverOpen] = useState(false);+ const [connectionToReplace, setConnectionToReplace] =+ useState<AppConnectionWithoutSensitiveData | null>(null);++ if (flowConnections.length === 0) {+ return null;+ }++ return (+ <>+ <Popover open={popoverOpen} onOpenChange={setPopoverOpen}>+ <PopoverTrigger asChild>+ <Button variant="ghost">+ <Plug className="w-4 h-4" />+ {t('Connections')}+ <span className="text-gray-11">{flowConnections.length}</span>+ </Button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-[340px] p-0">+ <PopoverHeader className="border-b px-4 py-3">+ <PopoverTitle>{t('Connections in this flow')}</PopoverTitle>+ {showReplace && (+ <PopoverDescription className="text-xs">+ {t('Replacing a connection updates every step that uses it.')}+ </PopoverDescription>+ )}+ </PopoverHeader>+ <ScrollArea viewPortClassName="max-h-[320px]">+ <div className="flex flex-col gap-1 p-2">+ {flowConnections.map(({ connection, stepCount }) => (+ <div+ key={connection.id}+ className="flex items-center gap-3 rounded-md px-2 py-2"+ >+ <PieceIconWithPieceName+ pieceName={connection.pieceName}+ size="sm"+ border={false}+ />+ <div className="flex min-w-0 flex-1 flex-col">+ <TextWithTooltip tooltipMessage={connection.displayName}>+ <p className="truncate text-sm">+ {connection.displayName}+ </p>+ </TextWithTooltip>+ <span className="text-xs text-gray-11">+ {t('usedInStepsCount', { count: stepCount })}+ </span>+ </div>+ {showReplace && (+ <PermissionNeededTooltip+ hasPermission={hasPermissionToReplace}+ >+ <Button+ variant="outline"+ size="sm"+ disabled={!hasPermissionToReplace || isFlowLocked}+ onClick={() => {+ setPopoverOpen(false);+ setConnectionToReplace(connection);+ }}+ >+ {t('Replace')}+ </Button>+ </PermissionNeededTooltip>+ )}+ </div>+ ))}+ </div>+ </ScrollArea>+ </PopoverContent>+ </Popover>+ {connectionToReplace && (+ <ReplaceConnectionForFlowDialog+ sourceConnection={connectionToReplace}+ open+ onOpenChange={(open) => {+ if (!open) {+ setConnectionToReplace(null);+ }+ }}+ />+ )}+ </>+ );+};diff --git a/packages/web/src/app/builder/builder-header/replace-connection-for-flow-dialog.tsx b/packages/web/src/app/builder/builder-header/replace-connection-for-flow-dialog.tsxindex 8961cbdb229..a4b4e2f4886 100644--- a/packages/web/src/app/builder/builder-header/replace-connection-for-flow-dialog.tsx+++ b/packages/web/src/app/builder/builder-header/replace-connection-for-flow-dialog.tsx@@ -1,8 +1,7 @@-import { flowStructureUtil, unique } from '@activepieces/shared';+import { AppConnectionWithoutSensitiveData } from '@activepieces/shared';import { useMutation } from '@tanstack/react-query';import { t } from 'i18next';import { Info } from 'lucide-react';-import React, { useState } from 'react';import { useForm } from 'react-hook-form';import { useBuilderStateContext } from '@/app/builder/builder-hooks';@@ -23,7 +22,6 @@ import {DialogFooter,DialogHeader,DialogTitle,- DialogTrigger,} from '@/components/ui/dialog';import { Form } from '@/components/ui/form';import { internalErrorToast } from '@/components/ui/sonner';@@ -31,30 +29,37 @@ import {appConnectionsMutations,appConnectionsQueries,} from '@/features/connections';-import { piecesHooks } from '@/features/pieces';+import { PieceIconWithPieceName } from '@/features/pieces';import { authenticationSession } from '@/lib/authentication-session';const ReplaceConnectionForFlowDialog = ({- children,-}: {- children: React.ReactNode;-}) => {- const [dialogOpen, setDialogOpen] = useState(false);+ sourceConnection,+ open,+ onOpenChange,+}: ReplaceConnectionForFlowDialogProps) => {return (- <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>- <DialogTrigger asChild>{children}</DialogTrigger>+ <Dialog open={open} onOpenChange={onOpenChange}><DialogContent className="flex flex-col"><DialogHeader>- <DialogTitle>{t('Replace connection')}</DialogTitle>+ <DialogTitle className="flex items-center gap-2">+ <PieceIconWithPieceName+ pieceName={sourceConnection.pieceName}+ size="sm"+ border={false}+ />+ {t('Replace {name}', { name: sourceConnection.displayName })}+ </DialogTitle><DialogDescription>{t(- 'Switch the steps of this flow from one connection to another. Other flows are not changed.',+ 'Every step in this flow that uses {name} will switch to the connection you pick below.',+ { name: sourceConnection.displayName },)}</DialogDescription></DialogHeader><ReplaceConnectionForFlowForm- key={dialogOpen ? 'open' : 'closed'}- setDialogOpen={setDialogOpen}+ key={open ? 'open' : 'closed'}+ sourceConnection={sourceConnection}+ setDialogOpen={onOpenChange}/></DialogContent></Dialog>@@ -62,8 +67,10 @@ const ReplaceConnectionForFlowDialog = ({};function ReplaceConnectionForFlowForm({+ sourceConnection,setDialogOpen,}: {+ sourceConnection: AppConnectionWithoutSensitiveData;setDialogOpen: (open: boolean) => void;}) {const [flow, savePendingEdits, showsNewestVersion] = useBuilderStateContext(@@ -72,17 +79,12 @@ function ReplaceConnectionForFlowForm({const refreshDraft = flowCanvasHooks.useRefreshDraftAndMakeNewDraftEditable();const { switchToDraft } = flowCanvasHooks.useSwitchToDraft();const projectId = authenticationSession.getProjectId()!;- const { pieces, isLoading: piecesLoading } = piecesHooks.usePieces({});const { data: connections, isLoading: connectionsLoading } =appConnectionsQueries.useAppConnections({request: { projectId, limit: 1000 },extraKeys: [projectId],staleTime: 0,});- const {- data: draftAndPublishedVersions,- isLoading: draftAndPublishedVersionsLoading,- } = flowCanvasHooks.useDraftAndPublishedVersions();const { mutate: replaceConnections, isPending: isReplacing } =appConnectionsMutations.useReplaceConnections({setDialogOpen,@@ -109,26 +111,14 @@ function ReplaceConnectionForFlowForm({const form = useForm<FlowReplaceFormValues>({defaultValues: {...replaceConnectionSelectionUtils.emptySelection(),+ pieceName: sourceConnection.pieceName,+ sourceConnectionId: sourceConnection.id,applyToPublishedVersions: false,},mode: 'onSubmit',});const projectConnections = connections?.data ?? [];- const flowConnectionExternalIds = unique(- (draftAndPublishedVersions ?? []).flatMap((flowVersion) =>- flowStructureUtil.extractConnectionIds(flowVersion),- ),- );- const flowConnections = projectConnections.filter((connection) =>- flowConnectionExternalIds.includes(connection.externalId),- );- const flowPieceNames = new Set(- flowConnections.map((connection) => connection.pieceName),- );- const flowPieces =- pieces?.filter((piece) => flowPieceNames.has(piece.name)) ?? [];-return (<Form {...form}><form@@ -139,20 +129,17 @@ function ReplaceConnectionForFlowForm({<Info className="size-4" /><AlertDescription>{t(- 'Steps that use the replaced connection keep their settings. Test your flow to make sure nothing breaks.',+ 'Test the flow after the replace to make sure every step still works.',)}</AlertDescription></Alert><ReplaceConnectionVersionsField /><ReplaceConnectionSelectionFields- pieces={flowPieces}- sourceConnections={flowConnections}+ pieces={[]}+ sourceConnections={[sourceConnection]}targetConnections={projectConnections}- loading={- piecesLoading ||- connectionsLoading ||- draftAndPublishedVersionsLoading- }+ loading={connectionsLoading}+ hideSourceFields/><DialogFooter><DialogClose asChild>@@ -175,3 +162,9 @@ export { ReplaceConnectionForFlowDialog };type FlowReplaceFormValues = ReplaceConnectionSelection & {applyToPublishedVersions: boolean;};++type ReplaceConnectionForFlowDialogProps = {+ sourceConnection: AppConnectionWithoutSensitiveData;+ open: boolean;+ onOpenChange: (open: boolean) => void;+};diff --git a/packages/web/src/app/builder/flow-canvas/hooks.tsx b/packages/web/src/app/builder/flow-canvas/hooks.tsxindex d2cec555146..56c703557d6 100644--- a/packages/web/src/app/builder/flow-canvas/hooks.tsx+++ b/packages/web/src/app/builder/flow-canvas/hooks.tsx@@ -3,6 +3,7 @@ import {FlowDraftUpdatedEvent,FlowRunStatus,FlowVersionState,+ flowStructureUtil,WebsocketClientEvent,RunEnvironment,isFlowRunStateTerminal,@@ -17,9 +18,11 @@ import { useDebouncedCallback } from 'use-debounce';import { useEmbedding } from '@/components/providers/embed-provider';import { useSocket } from '@/components/providers/socket-provider';import { internalErrorToast } from '@/components/ui/sonner';+import { appConnectionsQueries } from '@/features/connections';import { flowRunsApi, flowRunUtils } from '@/features/flow-runs';import { flowsApi } from '@/features/flows';import { useAuthorization } from '@/hooks/authorization-hooks';+import { authenticationSession } from '@/lib/authentication-session';import { editorSession } from '@/lib/editor-session';import { useBuilderStateContext, useBuilderStore } from '../builder-hooks';@@ -321,31 +324,27 @@ function isActiveElementInsideListMapperModeInput(): boolean {);}-const useDraftAndPublishedVersions = () => {- const [flowId, savePendingEdits] = useBuilderStateContext((state) => [- state.flow.id,- state.savePendingEdits,- ]);- return useQuery({- queryKey: ['draft-and-published-versions', flowId],- queryFn: async () => {- await savePendingEdits();- const draftFlow = await flowsApi.get(flowId);- const publishedVersionId = draftFlow.publishedVersionId;- if (- isNil(publishedVersionId) ||- publishedVersionId === draftFlow.version.id- ) {- return [draftFlow.version];- }- const publishedFlow = await flowsApi.get(flowId, {- versionId: publishedVersionId,- });- return [draftFlow.version, publishedFlow.version];- },- staleTime: 0,- gcTime: 0,- });+const useFlowConnections = () => {+ const [flowVersion] = useBuilderStateContext((state) => [state.flowVersion]);+ const projectId = authenticationSession.getProjectId()!;+ const { data: connections, isLoading } =+ appConnectionsQueries.useAppConnections({+ request: { projectId, limit: 1000 },+ extraKeys: [projectId],+ staleTime: 0,+ });+ const stepConnectionExternalIds = flowStructureUtil+ .getAllSteps(flowVersion.trigger)+ .map((step) => flowStructureUtil.extractStepConnectionIds(step));+ const flowConnections = (connections?.data ?? [])+ .map((connection) => ({+ connection,+ stepCount: stepConnectionExternalIds.filter((connectionExternalIds) =>+ connectionExternalIds.includes(connection.externalId),+ ).length,+ }))+ .filter(({ stepCount }) => stepCount > 0);+ return { flowConnections, isLoading };};export const flowCanvasHooks = {@@ -360,5 +359,5 @@ export const flowCanvasHooks = {useResizeCanvas,useSwitchToDraft,useListenToExistingRun,- useDraftAndPublishedVersions,+ useFlowConnections,};diff --git a/packages/web/src/app/builder/flow-canvas/widgets/publish-flow-reminder-widget.tsx b/packages/web/src/app/builder/flow-canvas/widgets/publish-flow-reminder-widget.tsxindex af1478e49bb..40a588f0f6e 100644--- a/packages/web/src/app/builder/flow-canvas/widgets/publish-flow-reminder-widget.tsx+++ b/packages/web/src/app/builder/flow-canvas/widgets/publish-flow-reminder-widget.tsx@@ -47,6 +47,7 @@ const PublishFlowReminderWidget = () => {run,savePendingEdits,refreshDraftAfterFailedSave,+ exitStepSettings,] = useBuilderStateContext((state) => [state.saving,state.isPublishing,@@ -60,6 +61,7 @@ const PublishFlowReminderWidget = () => {state.run,state.savePendingEdits,state.refreshDraftAfterFailedSave,+ state.exitStepSettings,]);const store = useBuilderStore();const showShouldPublishButton = useShouldShowPublishButton({@@ -87,7 +89,10 @@ const PublishFlowReminderWidget = () => {overWriteDraftWithVersion,fetchFlow: flowsApi.get,setFlow,- setVersion,+ setVersion: (version) => {+ setVersion(version);+ exitStepSettings();+ },}),},);diff --git a/packages/web/src/app/components/flow-actions-menu.tsx b/packages/web/src/app/components/flow-actions-menu.tsxindex 13b3456b3f4..32ec4701dac 100644--- a/packages/web/src/app/components/flow-actions-menu.tsx+++ b/packages/web/src/app/components/flow-actions-menu.tsx@@ -15,7 +15,6 @@ import {GalleryVerticalEnd,Import,Pencil,- Replace,Share2,Trash2,UploadCloud,@@ -25,7 +24,6 @@ import React, { useState } from 'react';import { useLocation } from 'react-router-dom';import { toast } from 'sonner';-import { ReplaceConnectionForFlowDialog } from '@/app/builder/builder-header/replace-connection-for-flow-dialog';import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';import { PermissionNeededTooltip } from '@/components/custom/permission-needed-tooltip';import { LoadingSpinner } from '@/components/custom/spinner';@@ -68,13 +66,11 @@ type FlowActionMenuProps = {insideBuilder: true;onVersionsListClick: () => void;savePendingEdits: () => Promise<void>;- isFlowLocked: boolean;}| {insideBuilder: false;onVersionsListClick: null;savePendingEdits: null;- isFlowLocked?: undefined;});@@ -91,12 +87,8 @@ const FlowActionMenu: React.FC<FlowActionMenuProps> = ({onVersionsListClick,insideBuilder,savePendingEdits,- isFlowLocked,}) => {const isRunsPage = useLocation().pathname.includes('/runs');- const showsDraftOrPublishedVersion =- flowVersion.state === FlowVersionState.DRAFT ||- flowVersion.id === flow.publishedVersionId;const { platform } = platformHooks.useCurrentPlatform();const openNewWindow = useNewWindow();const { gitSync } = gitSyncHooks.useGitSync(@@ -106,9 +98,6 @@ const FlowActionMenu: React.FC<FlowActionMenuProps> = ({const { checkAccess } = useAuthorization();const userHasPermissionToWriteFolder = checkAccess(Permission.WRITE_FOLDER);const userHasPermissionToUpdateFlow = checkAccess(Permission.WRITE_FLOW);- const userHasPermissionToReplaceAppConnection = checkAccess(- Permission.REPLACE_APP_CONNECTION,- );const userHasPermissionToPushToGit = checkAccess(Permission.WRITE_PROJECT_RELEASE,);@@ -329,28 +318,6 @@ const FlowActionMenu: React.FC<FlowActionMenuProps> = ({</div></DropdownMenuItem>)}- {insideBuilder &&- !isRunsPage &&- showsDraftOrPublishedVersion &&- !embedState.hideReplaceConnection && (- <PermissionNeededTooltip- hasPermission={userHasPermissionToReplaceAppConnection}- >- <ReplaceConnectionForFlowDialog>- <DropdownMenuItem- disabled={- !userHasPermissionToReplaceAppConnection || isFlowLocked- }- onSelect={(e) => e.preventDefault()}- >- <div className="flex cursor-pointer flex-row gap-2 items-center">- <Replace className="h-4 w-4" />- <span>{t('Replace connection')}</span>- </div>- </DropdownMenuItem>- </ReplaceConnectionForFlowDialog>- </PermissionNeededTooltip>- )}{!readonly &&insideBuilder &&!embedState.hideExportAndImportFlow && (diff --git a/packages/web/src/app/connections/replace-connection-selection-form.tsx b/packages/web/src/app/connections/replace-connection-selection-form.tsxindex 5c13a893bb4..c0b22955f1b 100644--- a/packages/web/src/app/connections/replace-connection-selection-form.tsx+++ b/packages/web/src/app/connections/replace-connection-selection-form.tsx@@ -26,6 +26,7 @@ const ReplaceConnectionSelectionFields = ({sourceConnections,targetConnections,loading,+ hideSourceFields = false,}: ReplaceConnectionSelectionFieldsProps) => {const form = useFormContext<ReplaceConnectionSelection>();const selectedPiece = useWatch({ control: form.control, name: 'pieceName' });@@ -45,77 +46,81 @@ const ReplaceConnectionSelectionFields = ({return (<>- <FormField- control={form.control}- name="pieceName"- rules={{ required: t('Please select a piece') }}- render={({ field }) => (- <div className="flex flex-col gap-2">- <Label>{t('Piece')}</Label>- <SearchableSelect- value={field.value}- onChange={(value) => {- field.onChange(value);- form.setValue('sourceConnectionId', '');- form.setValue('targetConnectionId', '');- }}- options={pieces.map((piece) => ({- label: piece.displayName,- value: piece.name,- }))}- placeholder={t('Select a piece')}- loading={loading}- valuesRendering={(value) => {- const piece = pieces.find(- (candidate) => candidate.name === value,- );- return (- <div className="flex gap-2 items-center">- <PieceIconWithPieceName- pieceName={piece!.name}- size="xs"- border={false}- />- <span>{piece!.displayName}</span>- </div>- );- }}- />- <FormMessage />- </div>- )}- />+ {!hideSourceFields && (+ <FormField+ control={form.control}+ name="pieceName"+ rules={{ required: t('Please select a piece') }}+ render={({ field }) => (+ <div className="flex flex-col gap-2">+ <Label>{t('Piece')}</Label>+ <SearchableSelect+ value={field.value}+ onChange={(value) => {+ field.onChange(value);+ form.setValue('sourceConnectionId', '');+ form.setValue('targetConnectionId', '');+ }}+ options={pieces.map((piece) => ({+ label: piece.displayName,+ value: piece.name,+ }))}+ placeholder={t('Select a piece')}+ loading={loading}+ valuesRendering={(value) => {+ const piece = pieces.find(+ (candidate) => candidate.name === value,+ );+ return (+ <div className="flex gap-2 items-center">+ <PieceIconWithPieceName+ pieceName={piece!.name}+ size="xs"+ border={false}+ />+ <span>{piece!.displayName}</span>+ </div>+ );+ }}+ />+ <FormMessage />+ </div>+ )}+ />+ )}{selectedPiece && (<>- <FormField- control={form.control}- name="sourceConnectionId"- rules={{ required: t('Please select a connection to replace') }}- render={({ field }) => (- <div className="flex flex-col gap-2">- <Label>{t('Connection to replace')}</Label>- <SearchableSelect- value={field.value}- loading={loading}- onChange={(value) => {- field.onChange(value ?? '');- form.setValue('targetConnectionId', '');- }}- options={toOptions(pieceSourceConnections)}- placeholder={t('Choose connection to replace')}- valuesRendering={(value) => (- <ConnectionLabel- connection={pieceSourceConnections.find(- (connection) => connection.id === value,- )}- />- )}- />- <FormMessage />- </div>- )}- />+ {!hideSourceFields && (+ <FormField+ control={form.control}+ name="sourceConnectionId"+ rules={{ required: t('Please select a connection to replace') }}+ render={({ field }) => (+ <div className="flex flex-col gap-2">+ <Label>{t('Connection to replace')}</Label>+ <SearchableSelect+ value={field.value}+ loading={loading}+ onChange={(value) => {+ field.onChange(value ?? '');+ form.setValue('targetConnectionId', '');+ }}+ options={toOptions(pieceSourceConnections)}+ placeholder={t('Choose connection to replace')}+ valuesRendering={(value) => (+ <ConnectionLabel+ connection={pieceSourceConnections.find(+ (connection) => connection.id === value,+ )}+ />+ )}+ />+ <FormMessage />+ </div>+ )}+ />+ )}<FormFieldcontrol={form.control}@@ -246,4 +251,5 @@ type ReplaceConnectionSelectionFieldsProps = {sourceConnections: AppConnectionWithoutSensitiveData[];targetConnections: AppConnectionWithoutSensitiveData[];loading: boolean;+ hideSourceFields?: boolean;};