Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(connections): replace a connection in one flow from the builder (#16765)

Abdul07c3018442aa
diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.json
index ce62b797f4f..19ec22d2156 100644
--- a/packages/web/public/locales/en/translation.json
+++ b/packages/web/public/locales/en/translation.json
@@ -831,6 +831,8 @@
"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",
diff --git a/packages/web/src/app/builder/builder-header/builder-header.tsx b/packages/web/src/app/builder/builder-header/builder-header.tsx
index b1fdf8399c0..2f52fecde49 100644
--- a/packages/web/src/app/builder/builder-header/builder-header.tsx
+++ b/packages/web/src/app/builder/builder-header/builder-header.tsx
@@ -47,7 +47,7 @@ import { flowCanvasConsts } from '../flow-canvas/utils/consts';
import { BuilderFlowStatusSection } from './flow-status';
-export const BuilderHeader = () => {
+export const BuilderHeader = ({ isFlowLocked }: { isFlowLocked: boolean }) => {
const [queryParams] = useSearchParams();
const navigate = useNavigate();
const queryClient = useQueryClient();
@@ -150,6 +150,7 @@ export const BuilderHeader = () => {
}}
insideBuilder={true}
savePendingEdits={savePendingEdits}
+ isFlowLocked={isFlowLocked}
flow={flow}
flowVersion={flowVersion}
readonly={readonly}
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.tsx
new file mode 100644
index 00000000000..8961cbdb229
--- /dev/null
+++ b/packages/web/src/app/builder/builder-header/replace-connection-for-flow-dialog.tsx
@@ -0,0 +1,177 @@
+import { flowStructureUtil, unique } 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';
+import { flowCanvasHooks } from '@/app/builder/flow-canvas/hooks';
+import {
+ ReplaceConnectionSelection,
+ ReplaceConnectionSelectionFields,
+ replaceConnectionSelectionUtils,
+ ReplaceConnectionVersionsField,
+} from '@/app/connections/replace-connection-selection-form';
+import { Alert, AlertDescription } from '@/components/ui/alert';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from '@/components/ui/dialog';
+import { Form } from '@/components/ui/form';
+import { internalErrorToast } from '@/components/ui/sonner';
+import {
+ appConnectionsMutations,
+ appConnectionsQueries,
+} from '@/features/connections';
+import { piecesHooks } from '@/features/pieces';
+import { authenticationSession } from '@/lib/authentication-session';
+
+const ReplaceConnectionForFlowDialog = ({
+ children,
+}: {
+ children: React.ReactNode;
+}) => {
+ const [dialogOpen, setDialogOpen] = useState(false);
+ return (
+ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
+ <DialogTrigger asChild>{children}</DialogTrigger>
+ <DialogContent className="flex flex-col">
+ <DialogHeader>
+ <DialogTitle>{t('Replace connection')}</DialogTitle>
+ <DialogDescription>
+ {t(
+ 'Switch the steps of this flow from one connection to another. Other flows are not changed.',
+ )}
+ </DialogDescription>
+ </DialogHeader>
+ <ReplaceConnectionForFlowForm
+ key={dialogOpen ? 'open' : 'closed'}
+ setDialogOpen={setDialogOpen}
+ />
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+function ReplaceConnectionForFlowForm({
+ setDialogOpen,
+}: {
+ setDialogOpen: (open: boolean) => void;
+}) {
+ const [flow, savePendingEdits, showsNewestVersion] = useBuilderStateContext(
+ (state) => [state.flow, state.savePendingEdits, state.showsNewestVersion],
+ );
+ 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,
+ connections: connections?.data ?? [],
+ refetch: () => {
+ if (showsNewestVersion()) {
+ refreshDraft().catch(() => internalErrorToast());
+ return;
+ }
+ switchToDraft();
+ },
+ });
+ const { mutate: saveEditsThenReplace, isPending: isSaving } = useMutation({
+ mutationFn: (_values: FlowReplaceFormValues) => savePendingEdits(),
+ onSuccess: (_, values) =>
+ replaceConnections({
+ flowIds: [flow.id],
+ projectId,
+ sourceAppConnectionId: values.sourceConnectionId,
+ targetAppConnectionId: values.targetConnectionId,
+ applyToPublishedVersions: values.applyToPublishedVersions,
+ }),
+ });
+ const form = useForm<FlowReplaceFormValues>({
+ defaultValues: {
+ ...replaceConnectionSelectionUtils.emptySelection(),
+ 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
+ onSubmit={form.handleSubmit((values) => saveEditsThenReplace(values))}
+ className="flex flex-col gap-4"
+ >
+ <Alert>
+ <Info className="size-4" />
+ <AlertDescription>
+ {t(
+ 'Steps that use the replaced connection keep their settings. Test your flow to make sure nothing breaks.',
+ )}
+ </AlertDescription>
+ </Alert>
+ <ReplaceConnectionVersionsField />
+ <ReplaceConnectionSelectionFields
+ pieces={flowPieces}
+ sourceConnections={flowConnections}
+ targetConnections={projectConnections}
+ loading={
+ piecesLoading ||
+ connectionsLoading ||
+ draftAndPublishedVersionsLoading
+ }
+ />
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button type="button" variant="ghost">
+ {t('Cancel')}
+ </Button>
+ </DialogClose>
+ <Button type="submit" loading={isSaving || isReplacing}>
+ {t('Replace')}
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ );
+}
+
+ReplaceConnectionForFlowDialog.displayName = 'ReplaceConnectionForFlowDialog';
+export { ReplaceConnectionForFlowDialog };
+
+type FlowReplaceFormValues = ReplaceConnectionSelection & {
+ applyToPublishedVersions: boolean;
+};
diff --git a/packages/web/src/app/builder/flow-canvas/hooks.tsx b/packages/web/src/app/builder/flow-canvas/hooks.tsx
index b01c7c3548e..d2cec555146 100644
--- a/packages/web/src/app/builder/flow-canvas/hooks.tsx
+++ b/packages/web/src/app/builder/flow-canvas/hooks.tsx
@@ -321,6 +321,33 @@ 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,
+ });
+};
+
export const flowCanvasHooks = {
useSetSocketListener,
useShowBuilderIsSavingWarningBeforeLeaving,
@@ -333,4 +360,5 @@ export const flowCanvasHooks = {
useResizeCanvas,
useSwitchToDraft,
useListenToExistingRun,
+ useDraftAndPublishedVersions,
};
diff --git a/packages/web/src/app/builder/flow-canvas/widgets/builder-banner.tsx b/packages/web/src/app/builder/flow-canvas/widgets/builder-banner.tsx
index 6d0ef204e6a..f8df660f876 100644
--- a/packages/web/src/app/builder/flow-canvas/widgets/builder-banner.tsx
+++ b/packages/web/src/app/builder/flow-canvas/widgets/builder-banner.tsx
@@ -1,4 +1,5 @@
import { isNil } from '@activepieces/core-utils';
+import { LockResourceResponse } from '@activepieces/shared';
import { RightSideBarType } from '@/app/builder/types';
import { ResourceLockWidget } from '@/components/custom/resource-lock-widget';
@@ -10,11 +11,9 @@ import { useBuilderStateContext } from '../../builder-hooks';
import { FlowApprovalBanner } from './flow-approval-banner';
import { PublishFlowReminderWidget } from './publish-flow-reminder-widget';
import { RunInfoWidget } from './run-info-widget';
-import { useFlowLock } from './use-flow-lock';
import { ViewingOldVersionWidget } from './viewing-old-version-widget';
-const BuilderBanner = () => {
- const { lockedBy, takeOver } = useFlowLock();
+const BuilderBanner = ({ lockedBy, takeOver }: BuilderBannerProps) => {
const [run, rightSidebar] = useBuilderStateContext((state) => [
state.run,
state.rightSidebar,
@@ -50,3 +49,8 @@ const BuilderBanner = () => {
BuilderBanner.displayName = 'BuilderBanner';
export { BuilderBanner };
+
+type BuilderBannerProps = {
+ lockedBy: LockResourceResponse['lock'];
+ takeOver: () => void;
+};
diff --git a/packages/web/src/app/builder/index.tsx b/packages/web/src/app/builder/index.tsx
index 352f915376c..1193904acb7 100644
--- a/packages/web/src/app/builder/index.tsx
+++ b/packages/web/src/app/builder/index.tsx
@@ -1,3 +1,4 @@
+import { isNil } from '@activepieces/core-utils';
import {
FlowActionType,
FlowTriggerType,
@@ -28,6 +29,7 @@ import { FlowCanvas } from './flow-canvas';
import { flowCanvasHooks } from './flow-canvas/hooks';
import { flowCanvasConsts } from './flow-canvas/utils/consts';
import { BuilderBanner } from './flow-canvas/widgets/builder-banner';
+import { useFlowLock } from './flow-canvas/widgets/use-flow-lock';
import { FlowVersionsList } from './flow-versions';
import { RunsList } from './run-list';
import { CursorPositionProvider } from './state/cursor-position-context';
@@ -41,6 +43,7 @@ const DEFAULT_MIN_SIZE = '400px';
const SPLIT_MODE_COLLAPSE_THRESHOLD_PX = 700;
const BuilderPage = () => {
+ const { lockedBy, takeOver } = useFlowLock();
const { platform } = platformHooks.useCurrentPlatform();
const [
rightSidebar,
@@ -150,7 +153,7 @@ const BuilderPage = () => {
return (
<div className="flex h-full w-full flex-col relative max-h-[100vh]">
<div className="z-40">
- <BuilderHeader />
+ <BuilderHeader isFlowLocked={!isNil(lockedBy)} />
</div>
<ResizablePanelGroup orientation="horizontal">
<ResizablePanel defaultSize="100%" id="flow-canvas">
@@ -161,7 +164,7 @@ const BuilderPage = () => {
></FlowCanvas>
</CursorPositionProvider>
- <BuilderBanner />
+ <BuilderBanner lockedBy={lockedBy} takeOver={takeOver} />
{middlePanelRef.current &&
middlePanelRef.current.clientWidth > 0 && (
<CanvasControls
diff --git a/packages/web/src/app/components/flow-actions-menu.tsx b/packages/web/src/app/components/flow-actions-menu.tsx
index 32ec4701dac..cc3908081a3 100644
--- a/packages/web/src/app/components/flow-actions-menu.tsx
+++ b/packages/web/src/app/components/flow-actions-menu.tsx
@@ -15,6 +15,7 @@ import {
GalleryVerticalEnd,
Import,
Pencil,
+ Replace,
Share2,
Trash2,
UploadCloud,
@@ -24,6 +25,7 @@ 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';
@@ -66,11 +68,13 @@ type FlowActionMenuProps = {
insideBuilder: true;
onVersionsListClick: () => void;
savePendingEdits: () => Promise<void>;
+ isFlowLocked: boolean;
}
| {
insideBuilder: false;
onVersionsListClick: null;
savePendingEdits: null;
+ isFlowLocked?: undefined;
}
);
@@ -87,8 +91,12 @@ 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(
@@ -98,6 +106,9 @@ const FlowActionMenu: React.FC<FlowActionMenuProps> = ({
const { checkAccess } = useAuthorization();
const userHasPermissionToWriteFolder = checkAccess(Permission.WRITE_FOLDER);
const userHasPermissionToUpdateFlow = checkAccess(Permission.WRITE_FLOW);
+ const userHasPermissionToWriteAppConnection = checkAccess(
+ Permission.WRITE_APP_CONNECTION,
+ );
const userHasPermissionToPushToGit = checkAccess(
Permission.WRITE_PROJECT_RELEASE,
);
@@ -318,6 +329,28 @@ const FlowActionMenu: React.FC<FlowActionMenuProps> = ({
</div>
</DropdownMenuItem>
)}
+ {insideBuilder &&
+ !isRunsPage &&
+ showsDraftOrPublishedVersion &&
+ !embedState.isEmbedded && (
+ <PermissionNeededTooltip
+ hasPermission={userHasPermissionToWriteAppConnection}
+ >
+ <ReplaceConnectionForFlowDialog>
+ <DropdownMenuItem
+ disabled={
+ !userHasPermissionToWriteAppConnection || 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 && (