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): rebuild the project replace connection dialog (#16875)

Abdul4b9e824762cf
diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.json
index a05493b72f1..ce62b797f4f 100644
--- a/packages/web/public/locales/en/translation.json
+++ b/packages/web/public/locales/en/translation.json
@@ -827,7 +827,7 @@
"Select a piece": "Select a piece",
"Connection to replace": "Connection to replace",
"Choose connection to replace": "Choose connection to replace",
- "Replaced With": "Replaced With",
+ "Replace with": "Replace with",
"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}}",
@@ -835,11 +835,7 @@
"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",
"Draft and published": "Draft and published",
- "After replacing": "After replacing",
- "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.": "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.",
- "Keep the old connection": "Keep the old connection",
- "Delete the old connection": "Delete the old connection",
- "MCP servers are not updated automatically — reconnect them manually.": "MCP servers are not updated automatically — reconnect them manually.",
+ "This project needs approval to publish. Each affected flow gets a new publish request, which replaces any request that is already waiting for that flow.": "This project needs approval to publish. Each affected flow gets a new publish request, which replaces any request that is already waiting for that flow.",
"Disable Secret Manager": "Disable Secret Manager",
"Use Secret Manager": "Use Secret Manager",
"Select connection": "Select connection",
@@ -3341,7 +3337,7 @@
"Connection is working.": "Connection is working.",
"Connection failed": "Connection failed",
"This connection is no longer working. Reconnect it.": "This connection is no longer working. Reconnect it.",
- "Connections replaced successfully": "Connections replaced successfully",
+ "Replaced connection {sourceName} with connection {targetName}": "Replaced connection {sourceName} with connection {targetName}",
"Failed to replace connections": "Failed to replace connections",
"Connection has been updated.": "Connection has been updated.",
"OAuth2 Credentials Deleted": "OAuth2 Credentials Deleted",
@@ -3719,5 +3715,7 @@
"Add license key": "Add license key",
"Your license doesn’t include worker groups": "Your license doesn’t include worker groups",
"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."
+ "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:"
}
diff --git a/packages/web/src/app/connections/delete-connections-dialog.tsx b/packages/web/src/app/connections/delete-connections-dialog.tsx
new file mode 100644
index 00000000000..a5c8144ad83
--- /dev/null
+++ b/packages/web/src/app/connections/delete-connections-dialog.tsx
@@ -0,0 +1,98 @@
+import { AppConnectionWithoutSensitiveData } from '@activepieces/shared';
+import { t } from 'i18next';
+import { BotIcon, WorkflowIcon } from 'lucide-react';
+
+import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';
+import { DeleteConnectionWarning } from '@/components/custom/global-connection-utils';
+import { Badge } from '@/components/ui/badge';
+import { ScrollArea } from '@/components/ui/scroll-area';
+import { appConnectionsQueries } from '@/features/connections';
+import { AdminControl } from '@/lib/admin-control';
+
+function DeleteConnectionsDialog({
+ connections,
+ title,
+ message,
+ mutationFn,
+ open,
+ onOpenChange,
+ controlId,
+ children,
+}: DeleteConnectionsDialogProps) {
+ const {
+ data: usage,
+ isLoading,
+ isError,
+ } = appConnectionsQueries.useFlowsAndAgentsUsingConnections({
+ connections,
+ enabled: open,
+ });
+ const flows = usage?.flows ?? [];
+ const agents = usage?.agents ?? [];
+ const stillUsed = flows.length > 0 || agents.length > 0;
+
+ return (
+ <ConfirmationDeleteDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ title={title}
+ message={message}
+ warning={
+ isError ? (
+ <DeleteConnectionWarning />
+ ) : stillUsed ? (
+ <div className="flex flex-col gap-2">
+ {t(
+ 'These still use the connection and stop working if you delete it:',
+ )}
+ <ScrollArea viewPortClassName="max-h-[250px]">
+ <div className="flex flex-wrap gap-1.5">
+ {flows.map((flow) => (
+ <Badge
+ key={flow.id}
+ variant="secondary"
+ className="max-w-[200px]"
+ >
+ <WorkflowIcon className="w-3 h-3 shrink-0" />
+ <span className="truncate">{flow.version.displayName}</span>
+ </Badge>
+ ))}
+ {agents.map((agent) => (
+ <Badge
+ key={agent.id}
+ variant="secondary"
+ className="max-w-[200px]"
+ >
+ <BotIcon className="w-3 h-3 shrink-0" />
+ <span className="truncate">{agent.displayName}</span>
+ </Badge>
+ ))}
+ </div>
+ </ScrollArea>
+ </div>
+ ) : undefined
+ }
+ mutationFn={mutationFn}
+ entityName={t('connection')}
+ buttonText={t('Delete')}
+ confirmDisabled={isLoading || isError}
+ controlId={controlId}
+ showToast
+ >
+ {children}
+ </ConfirmationDeleteDialog>
+ );
+}
+
+export { DeleteConnectionsDialog };
+
+type DeleteConnectionsDialogProps = {
+ connections: AppConnectionWithoutSensitiveData[];
+ title: string;
+ message: string;
+ mutationFn: () => Promise<void>;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ controlId?: AdminControl;
+ children?: React.ReactNode;
+};
diff --git a/packages/web/src/app/connections/replace-connection-for-project-dialog.tsx b/packages/web/src/app/connections/replace-connection-for-project-dialog.tsx
new file mode 100644
index 00000000000..cccac7ce054
--- /dev/null
+++ b/packages/web/src/app/connections/replace-connection-for-project-dialog.tsx
@@ -0,0 +1,325 @@
+import { t } from 'i18next';
+import { ChevronDown, WorkflowIcon } from 'lucide-react';
+import React, { useState } from 'react';
+import { useForm, useWatch } from 'react-hook-form';
+import { useNavigate } from 'react-router-dom';
+
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from '@/components/ui/collapsible';
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from '@/components/ui/dialog';
+import { Form } from '@/components/ui/form';
+import { ScrollArea } from '@/components/ui/scroll-area';
+import {
+ appConnectionsMutations,
+ appConnectionsQueries,
+} from '@/features/connections';
+import { flowHooks } from '@/features/flows';
+import { piecesHooks } from '@/features/pieces';
+
+import {
+ ReplaceConnectionSelection,
+ ReplaceConnectionSelectionFields,
+ replaceConnectionSelectionUtils,
+ ReplaceConnectionVersionsField,
+} from './replace-connection-selection-form';
+
+const ReplaceConnectionForProjectDialog = ({
+ onConnectionMerged,
+ children,
+ projectId,
+}: ReplaceConnectionForProjectDialogProps) => {
+ const [dialogOpen, setDialogOpen] = useState(false);
+ return (
+ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
+ <DialogTrigger asChild>{children}</DialogTrigger>
+ <DialogContent className="flex flex-col">
+ <ReplaceConnectionForProjectForm
+ key={dialogOpen ? 'open' : 'closed'}
+ projectId={projectId}
+ onConnectionMerged={onConnectionMerged}
+ setDialogOpen={setDialogOpen}
+ />
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+function ReplaceConnectionForProjectForm({
+ projectId,
+ onConnectionMerged,
+ setDialogOpen,
+}: ReplaceConnectionForProjectFormProps) {
+ const navigate = useNavigate();
+ const [step, setStep] = useState<ProjectReplaceStep>(
+ ProjectReplaceStep.CHOOSE_CONNECTIONS,
+ );
+ const { pieces, isLoading: piecesLoading } = piecesHooks.usePieces({});
+ const { data: connections, isLoading: connectionsLoading } =
+ appConnectionsQueries.useAppConnections({
+ request: { projectId, limit: 1000 },
+ extraKeys: [projectId],
+ staleTime: 0,
+ });
+
+ const { mutate: replaceConnections, isPending: isReplacing } =
+ appConnectionsMutations.useReplaceConnections({
+ setDialogOpen,
+ connections: connections?.data ?? [],
+ refetch: onConnectionMerged,
+ });
+
+ const {
+ mutate: fetchAffectedFlows,
+ data: flowsUsingConnection,
+ isPending: isFetchingAffectedFlows,
+ } = flowHooks.useListFlowsUsingConnection({
+ projectId,
+ onSuccess: () => setStep(ProjectReplaceStep.REVIEW_AFFECTED_FLOWS),
+ });
+
+ const form = useForm<ProjectReplaceFormValues>({
+ defaultValues: {
+ ...replaceConnectionSelectionUtils.emptySelection(),
+ applyToPublishedVersions: false,
+ },
+ mode: 'onSubmit',
+ });
+ const sourceConnectionId = useWatch({
+ control: form.control,
+ name: 'sourceConnectionId',
+ });
+ const applyToPublishedVersions = useWatch({
+ control: form.control,
+ name: 'applyToPublishedVersions',
+ });
+
+ const projectConnections = connections?.data ?? [];
+ const connectionPieceNames = new Set(
+ projectConnections.map((connection) => connection.pieceName),
+ );
+ const replaceablePieces =
+ pieces?.filter(
+ (piece) =>
+ !PIECES_WITHOUT_REPLACE.includes(piece.name) &&
+ connectionPieceNames.has(piece.name),
+ ) ?? [];
+
+ const sourceConnection = projectConnections.find(
+ (connection) => connection.id === sourceConnectionId,
+ );
+ const draftFlows = flowsUsingConnection?.draftFlows ?? [];
+ const publishedOnlyFlows = flowsUsingConnection?.publishedOnlyFlows ?? [];
+ const affectedFlows = (
+ applyToPublishedVersions
+ ? [...draftFlows, ...publishedOnlyFlows]
+ : draftFlows
+ ).slice(0, MAX_FLOWS_PER_REPLACE);
+
+ const handleSubmit = (values: ProjectReplaceFormValues) => {
+ if (step === ProjectReplaceStep.CHOOSE_CONNECTIONS) {
+ if (sourceConnection) {
+ fetchAffectedFlows(sourceConnection.externalId);
+ }
+ return;
+ }
+ replaceConnections({
+ sourceAppConnectionId: values.sourceConnectionId,
+ targetAppConnectionId: values.targetConnectionId,
+ projectId,
+ applyToPublishedVersions: values.applyToPublishedVersions,
+ flowIds: affectedFlows.map((flow) => flow.id),
+ });
+ };
+
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>
+ {step === ProjectReplaceStep.CHOOSE_CONNECTIONS
+ ? t('Replace connection')
+ : t('Review and confirm')}
+ </DialogTitle>
+ <DialogDescription>
+ {step === ProjectReplaceStep.CHOOSE_CONNECTIONS
+ ? t(
+ 'Switch flows from one connection to another. Choose the connection to replace and the one to use instead.',
+ )
+ : t('Review what changes, then replace.')}
+ </DialogDescription>
+ </DialogHeader>
+
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(handleSubmit)}
+ className="flex flex-col gap-4"
+ >
+ {step === ProjectReplaceStep.CHOOSE_CONNECTIONS ? (
+ <>
+ <ReplaceConnectionSelectionFields
+ pieces={replaceablePieces}
+ sourceConnections={projectConnections}
+ targetConnections={projectConnections}
+ loading={piecesLoading || connectionsLoading}
+ />
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button type="button" variant="ghost">
+ {t('Cancel')}
+ </Button>
+ </DialogClose>
+ <Button type="submit" loading={isFetchingAffectedFlows}>
+ {t('Next')}
+ </Button>
+ </DialogFooter>
+ </>
+ ) : (
+ <>
+ {affectedFlows.length === 0 ? (
+ <div className="flex items-center gap-2 rounded-md border border-dashed px-3 py-2.5 text-sm text-gray-11">
+ <WorkflowIcon className="w-4 h-4 shrink-0" />
+ {t('No flows use this connection yet')}
+ </div>
+ ) : (
+ <Collapsible defaultOpen className="rounded-md border">
+ <CollapsibleTrigger className="group flex w-full items-center justify-between gap-2 px-3 py-2.5 text-sm font-medium">
+ <span>
+ {t('flowsUsingConnection', {
+ count: affectedFlows.length,
+ })}
+ </span>
+ <ChevronDown className="w-4 h-4 shrink-0 text-gray-11 transition-transform group-data-[state=closed]:-rotate-90" />
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ <ScrollArea
+ className="px-3 pb-3"
+ viewPortClassName="max-h-[250px]"
+ >
+ <div className="flex flex-wrap gap-1.5">
+ {affectedFlows.map((flow) => (
+ <Badge
+ key={flow.id}
+ variant="secondary"
+ className="max-w-[280px] cursor-pointer hover:bg-gray-3/70"
+ onClick={() =>
+ navigate(
+ `/projects/${flow.projectId}/flows/${flow.id}`,
+ )
+ }
+ >
+ <WorkflowIcon className="w-3 h-3 shrink-0" />
+ <span className="truncate">
+ {flow.version.displayName}
+ </span>
+ <span className="shrink-0 text-gray-11">
+ {versionsUsingConnectionLabel({
+ usedInDraft:
+ flowsUsingConnection?.draftFlowIds.has(
+ flow.id,
+ ) ?? false,
+ usedInPublished:
+ flowsUsingConnection?.publishedFlowIds.has(
+ flow.id,
+ ) ?? false,
+ })}
+ </span>
+ </Badge>
+ ))}
+ </div>
+ </ScrollArea>
+ </CollapsibleContent>
+ </Collapsible>
+ )}
+
+ <ReplaceConnectionVersionsField />
+
+ <span className="text-xs text-gray-11">
+ {t('A replace changes up to {max} flows.', {
+ max: MAX_FLOWS_PER_REPLACE,
+ })}
+ </span>
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={() => {
+ form.setValue('applyToPublishedVersions', false);
+ setStep(ProjectReplaceStep.CHOOSE_CONNECTIONS);
+ }}
+ >
+ {t('Back')}
+ </Button>
+ <Button
+ type="submit"
+ loading={isReplacing}
+ disabled={affectedFlows.length === 0}
+ >
+ {t('Replace')}
+ </Button>
+ </DialogFooter>
+ </>
+ )}
+ </form>
+ </Form>
+ </>
+ );
+}
+
+function versionsUsingConnectionLabel({
+ usedInDraft,
+ usedInPublished,
+}: {
+ usedInDraft: boolean;
+ usedInPublished: boolean;
+}): string {
+ if (usedInDraft && usedInPublished) {
+ return t('Draft and published');
+ }
+ return usedInPublished ? t('Published') : t('Draft');
+}
+
+ReplaceConnectionForProjectDialog.displayName =
+ 'ReplaceConnectionForProjectDialog';
+export { ReplaceConnectionForProjectDialog };
+
+const MAX_FLOWS_PER_REPLACE = 200;
+
+const PIECES_WITHOUT_REPLACE = [
+ '@activepieces/piece-mcp',
+ '@activepieces/piece-webhook',
+];
+
+type ReplaceConnectionForProjectDialogProps = {
+ onConnectionMerged: () => void;
+ children: React.ReactNode;
+ projectId: string;
+};
+
+type ReplaceConnectionForProjectFormProps = {
+ projectId: string;
+ onConnectionMerged: () => void;
+ setDialogOpen: (open: boolean) => void;
+};
+
+type ProjectReplaceFormValues = ReplaceConnectionSelection & {
+ applyToPublishedVersions: boolean;
+};
+
+enum ProjectReplaceStep {
+ CHOOSE_CONNECTIONS = 'CHOOSE_CONNECTIONS',
+ REVIEW_AFFECTED_FLOWS = 'REVIEW_AFFECTED_FLOWS',
+}
diff --git a/packages/web/src/app/connections/replace-connection-selection-form.tsx b/packages/web/src/app/connections/replace-connection-selection-form.tsx
new file mode 100644
index 00000000000..5c13a893bb4
--- /dev/null
+++ b/packages/web/src/app/connections/replace-connection-selection-form.tsx
@@ -0,0 +1,249 @@
+import { PieceMetadataModelSummary } from '@activepieces/pieces-framework';
+import {
+ AppConnectionScope,
+ AppConnectionWithoutSensitiveData,
+} from '@activepieces/shared';
+import { t } from 'i18next';
+import { GlobeIcon, Info } from 'lucide-react';
+import { useFormContext, useWatch } from 'react-hook-form';
+
+import { SearchableSelect } from '@/components/custom/searchable-select';
+import { Alert, AlertDescription } from '@/components/ui/alert';
+import { FormField, FormMessage } from '@/components/ui/form';
+import { Label, LabelWithTooltip } from '@/components/ui/label';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { flowApprovalsHooks } from '@/features/flow-approvals';
+import { PieceIconWithPieceName } from '@/features/pieces';
+
+const ReplaceConnectionSelectionFields = ({
+ pieces,
+ sourceConnections,
+ targetConnections,
+ loading,
+}: ReplaceConnectionSelectionFieldsProps) => {
+ const form = useFormContext<ReplaceConnectionSelection>();
+ const selectedPiece = useWatch({ control: form.control, name: 'pieceName' });
+ const sourceConnectionId = useWatch({
+ control: form.control,
+ name: 'sourceConnectionId',
+ });
+
+ const pieceSourceConnections = sourceConnections.filter(
+ (connection) => connection.pieceName === selectedPiece,
+ );
+ const pieceTargetConnections = targetConnections.filter(
+ (connection) =>
+ connection.pieceName === selectedPiece &&
+ connection.id !== sourceConnectionId,
+ );
+
+ 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>
+ )}
+ />
+
+ {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>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="targetConnectionId"
+ rules={{
+ required: t('Please select a connection to replace with'),
+ }}
+ render={({ field }) => (
+ <div className="flex flex-col gap-2">
+ <Label>{t('Replace with')}</Label>
+ <SearchableSelect
+ value={field.value}
+ loading={loading}
+ onChange={(value) => field.onChange(value ?? '')}
+ options={toOptions(pieceTargetConnections)}
+ placeholder={t('Choose connection to replace with')}
+ valuesRendering={(value) => (
+ <ConnectionLabel
+ connection={pieceTargetConnections.find(
+ (connection) => connection.id === value,
+ )}
+ />
+ )}
+ />
+ <FormMessage />
+ </div>
+ )}
+ />
+ </>
+ )}
+ </>
+ );
+};
+
+function ConnectionLabel({
+ connection,
+}: {
+ connection: AppConnectionWithoutSensitiveData | undefined;
+}) {
+ if (!connection) {
+ return null;
+ }
+ return (
+ <div className="flex gap-2 items-center">
+ <PieceIconWithPieceName
+ pieceName={connection.pieceName}
+ size="xs"
+ border={false}
+ />
+ {connection.scope === AppConnectionScope.PLATFORM && (
+ <GlobeIcon className="w-4 h-4" />
+ )}
+ <span>{connection.displayName}</span>
+ </div>
+ );
+}
+
+function toOptions(connections: AppConnectionWithoutSensitiveData[]) {
+ return connections.map((connection) => ({
+ label: connection.displayName,
+ value: connection.id,
+ }));
+}
+
+function ReplaceConnectionVersionsField() {
+ const form = useFormContext<{ applyToPublishedVersions: boolean }>();
+ const publishNeedsApproval = flowApprovalsHooks.usePublishNeedsApproval();
+ return (
+ <FormField
+ control={form.control}
+ name="applyToPublishedVersions"
+ render={({ field }) => (
+ <div className="flex flex-col gap-1.5">
+ <LabelWithTooltip
+ label={t('Which versions to update')}
+ tooltip={t(
+ '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.',
+ )}
+ />
+ <Select
+ value={String(field.value)}
+ onValueChange={(value) => field.onChange(value === 'true')}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="false">{t('Draft only')}</SelectItem>
+ <SelectItem value="true">{t('Draft and published')}</SelectItem>
+ </SelectContent>
+ </Select>
+ {field.value && publishNeedsApproval && (
+ <Alert>
+ <Info className="size-4" />
+ <AlertDescription>
+ {t(
+ 'This project needs approval to publish. Each affected flow gets a new publish request, which replaces any request that is already waiting for that flow.',
+ )}
+ </AlertDescription>
+ </Alert>
+ )}
+ </div>
+ )}
+ />
+ );
+}
+
+ReplaceConnectionSelectionFields.displayName =
+ 'ReplaceConnectionSelectionFields';
+export { ReplaceConnectionSelectionFields, ReplaceConnectionVersionsField };
+
+export const replaceConnectionSelectionUtils = {
+ emptySelection: (): ReplaceConnectionSelection => ({
+ pieceName: '',
+ sourceConnectionId: '',
+ targetConnectionId: '',
+ }),
+};
+
+export type ReplaceConnectionSelection = {
+ pieceName: string;
+ sourceConnectionId: string;
+ targetConnectionId: string;
+};
+
+type ReplaceConnectionSelectionFieldsProps = {
+ pieces: PieceMetadataModelSummary[];
+ sourceConnections: AppConnectionWithoutSensitiveData[];
+ targetConnections: AppConnectionWithoutSensitiveData[];
+ loading: boolean;
+};
diff --git a/packages/web/src/app/connections/replace-connections-dialog.tsx b/packages/web/src/app/connections/replace-connections-dialog.tsx
deleted file mode 100644
index b0aae7bc9c1..00000000000
--- a/packages/web/src/app/connections/replace-connections-dialog.tsx
+++ /dev/null
@@ -1,526 +0,0 @@
-import { AppConnectionScope, PopulatedFlow } from '@activepieces/shared';
-import { useMutation } from '@tanstack/react-query';
-import { t } from 'i18next';
-import { ChevronDown, GlobeIcon, Info, WorkflowIcon } from 'lucide-react';
-import React, { useState, useMemo } from 'react';
-import { FieldErrors, useForm, useWatch } from 'react-hook-form';
-import { useNavigate } from 'react-router-dom';
-import { toast } from 'sonner';
-
-import { LogoPlate } from '@/components/custom/logo-plate';
-import { SearchableSelect } from '@/components/custom/searchable-select';
-import { Badge } from '@/components/ui/badge';
-import { Button } from '@/components/ui/button';
-import {
- Collapsible,
- CollapsibleContent,
- CollapsibleTrigger,
-} from '@/components/ui/collapsible';
-import {
- Dialog,
- DialogClose,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
-} from '@/components/ui/dialog';
-import { Form, FormField, FormMessage } from '@/components/ui/form';
-import { Label } from '@/components/ui/label';
-import { ScrollArea } from '@/components/ui/scroll-area';
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from '@/components/ui/select';
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from '@/components/ui/tooltip';
-import {
- appConnectionsMutations,
- appConnectionsQueries,
-} from '@/features/connections';
-import { flowsApi } from '@/features/flows';
-import { PieceIconWithPieceName, piecesHooks } from '@/features/pieces';
-
-type ReplaceConnectionsDialogProps = {
- onConnectionMerged: () => void;
- children: React.ReactNode;
- projectId: string;
-};
-
-type FormData = {
- pieceName: string;
- sourceConnections: { id: string; externalId: string };
- replacedWithConnection: { id: string; externalId: string };
-};
-
-type VersionScope = 'draft' | 'published';
-
-enum STEP {
- SELECT = 'SELECT',
- CONFIRM = 'CONFIRM',
-}
-
-const ReplaceConnectionsDialog = ({
- onConnectionMerged,
- children,
- projectId,
-}: ReplaceConnectionsDialogProps) => {
- const [dialogOpen, setDialogOpen] = useState(false);
- const [step, setStep] = useState<STEP>(STEP.SELECT);
- const [affectedFlows, setAffectedFlows] = useState<Array<PopulatedFlow>>([]);
- const [versionScope, setVersionScope] = useState<VersionScope>('draft');
- const { pieces, isLoading: piecesLoading } = piecesHooks.usePieces({});
-
- const { data: connections, isLoading: connectionsLoading } =
- appConnectionsQueries.useAppConnections({
- request: {
- projectId,
- limit: 1000,
- },
- extraKeys: [projectId, dialogOpen],
- enabled: dialogOpen,
- });
-
- const { mutate: replaceConnections, isPending: isReplacing } =
- appConnectionsMutations.useReplaceConnections({
- setDialogOpen,
- refetch: onConnectionMerged,
- });
-
- const { mutate: fetchAffectedFlows, isPending: isFetchingAffectedFlows } =
- useMutation({
- mutationFn: async (externalId: string) => {
- const response = await flowsApi.list({
- projectId: projectId,
- connectionExternalIds: [externalId],
- cursor: undefined,
- limit: 1000,
- });
- return response;
- },
- onSuccess: (data) => {
- setAffectedFlows(data.data);
- setStep(STEP.CONFIRM);
- },
- onError: () => {
- toast.error(t('Error'), {
- description: t('Failed to get affected flows'),
- });
- },
- });
-
- const form = useForm<FormData>({
- defaultValues: {
- pieceName: '',
- sourceConnections: { id: '', externalId: '' },
- replacedWithConnection: { id: '', externalId: '' },
- },
- mode: 'onSubmit',
- resolver: (values) => {
- const errors: FieldErrors<FormData> = {};
-
- if (!values.pieceName) {
- errors.pieceName = {
- type: 'required',
- message: t('Please select a piece'),
- };
- }
-
- if (!values.sourceConnections?.id) {
- errors.sourceConnections = {
- type: 'required',
- message: t('Please select a connection to replace'),
- };
- }
-
- if (!values.replacedWithConnection?.id) {
- errors.replacedWithConnection = {
- type: 'required',
- message: t('Please select a connection to replace with'),
- };
- }
-
- return {
- values: Object.keys(errors).length === 0 ? values : {},
- errors,
- };
- },
- });
-
- const selectedPiece = form.watch('pieceName');
-
- const connectionPieceNames = new Set(
- connections?.data.map((conn) => conn.pieceName),
- );
-
- const piecesOptions =
- pieces
- ?.filter(
- (piece) =>
- piece.name !== '@activepieces/piece-mcp' &&
- piece.name !== '@activepieces/piece-webhook' &&
- connectionPieceNames.has(piece.name),
- )
- .map((piece) => ({
- label: piece.displayName,
- value: piece.name,
- })) ?? [];
-
- const filteredConnections =
- connections?.data.filter((conn) => conn.pieceName === selectedPiece) ?? [];
-
- const sourceConnectionId = useWatch({
- control: form.control,
- name: 'sourceConnections.id',
- });
-
- const replacedWithOptions = useMemo(() => {
- return filteredConnections
- .filter((conn) => conn.id !== sourceConnectionId)
- .map((conn) => ({
- label: conn.displayName,
- value: conn.id,
- }));
- }, [filteredConnections, sourceConnectionId]);
-
- const applyToPublishedVersions = versionScope === 'published';
-
- const handleBack = () => {
- setStep(STEP.SELECT);
- setAffectedFlows([]);
- setVersionScope('draft');
- };
-
- const handleConfirmedSubmit = async (values: FormData) => {
- const isValid = await form.trigger();
- if (!isValid) {
- form.trigger([
- 'pieceName',
- 'sourceConnections',
- 'replacedWithConnection',
- ]);
- return;
- }
-
- replaceConnections({
- flowIds: affectedFlows.map((flow) => flow.id),
- sourceAppConnectionId: values.sourceConnections.id,
- targetAppConnectionId: values.replacedWithConnection.id,
- projectId: projectId,
- applyToPublishedVersions,
- });
- };
-
- const handleDialogOpenChange = (open: boolean) => {
- setDialogOpen(open);
- form.reset();
- setStep(STEP.SELECT);
- setAffectedFlows([]);
- setVersionScope('draft');
- };
- const navigate = useNavigate();
-
- return (
- <Dialog open={dialogOpen} onOpenChange={handleDialogOpenChange}>
- <DialogTrigger asChild>{children}</DialogTrigger>
- <DialogContent className="flex flex-col">
- <DialogHeader>
- <DialogTitle>
- {step === STEP.SELECT
- ? t('Replace connection')
- : t('Review and confirm')}
- </DialogTitle>
- <DialogDescription>
- {step === STEP.SELECT
- ? t(
- 'Switch flows from one connection to another. Choose the connection to replace and the one to use instead.',
- )
- : t('Review what changes, then replace.')}
- </DialogDescription>
- </DialogHeader>
-
- {step === STEP.SELECT ? (
- <Form {...form}>
- <form
- onSubmit={form.handleSubmit((data) =>
- fetchAffectedFlows(data.sourceConnections.externalId),
- )}
- className="flex flex-col gap-4"
- >
- <FormField
- control={form.control}
- name="pieceName"
- render={({ field }) => (
- <div className="flex flex-col gap-2">
- <Label>{t('Piece')}</Label>
- <SearchableSelect
- value={field.value}
- onChange={(value) => {
- field.onChange(value);
- form.setValue('sourceConnections', {
- id: '',
- externalId: '',
- });
- form.setValue('replacedWithConnection', {
- id: '',
- externalId: '',
- });
- }}
- options={piecesOptions}
- placeholder={t('Select a piece')}
- loading={piecesLoading}
- valuesRendering={(value) => {
- const piece = pieces?.find((p) => p.name === value);
- return (
- <div className="flex gap-2 items-center">
- <LogoPlate
- src={piece!.logoUrl}
- alt={piece!.displayName}
- size="xxs"
- />
- <span>{piece!.displayName}</span>
- </div>
- );
- }}
- />
- <FormMessage />
- </div>
- )}
- />
-
- {selectedPiece && (
- <>
- <FormField
- control={form.control}
- name="sourceConnections"
- render={({ field }) => (
- <div className="flex flex-col gap-2">
- <Label>{t('Connection to replace')}</Label>
- <SearchableSelect
- value={field.value?.id}
- loading={connectionsLoading}
- onChange={(value) => {
- const selectedConnection = filteredConnections.find(
- (c) => c.id === value,
- );
- field.onChange({
- id: selectedConnection?.id || '',
- externalId: selectedConnection?.externalId || '',
- });
- form.setValue('replacedWithConnection', {
- id: '',
- externalId: '',
- });
- }}
- options={filteredConnections.map((conn) => ({
- label: conn.displayName,
- value: conn.id,
- }))}
- placeholder={t('Choose connection to replace')}
- valuesRendering={(value) => {
- const conn = filteredConnections.find(
- (c) => c.id === value,
- );
- return (
- <div className="flex gap-2 items-center">
- <PieceIconWithPieceName
- pieceName={conn!.pieceName}
- size="xs"
- border={false}
- />
- {conn?.scope ===
- AppConnectionScope.PLATFORM && (
- <GlobeIcon className="w-4 h-4" />
- )}
- <span>{conn!.displayName}</span>
- </div>
- );
- }}
- />
- <FormMessage />
- </div>
- )}
- />
-
- {selectedPiece && (
- <FormField
- control={form.control}
- name="replacedWithConnection"
- render={({ field }) => (
- <div className="flex flex-col gap-2">
- <Label>{t('Replaced With')}</Label>
- <SearchableSelect
- value={field.value?.id}
- loading={connectionsLoading}
- onChange={(value) => {
- const selectedConnection =
- filteredConnections.find((c) => c.id === value);
- field.onChange({
- id: selectedConnection?.id || '',
- externalId:
- selectedConnection?.externalId || '',
- });
- }}
- options={replacedWithOptions}
- placeholder={t('Choose connection to replace with')}
- valuesRendering={(value) => {
- const conn = filteredConnections.find(
- (c) => c.id === value,
- );
- return (
- <div className="flex gap-2 items-center">
- <PieceIconWithPieceName
- pieceName={conn!.pieceName}
- size="xs"
- border={false}
- />
- {conn?.scope ===
- AppConnectionScope.PLATFORM && (
- <GlobeIcon className="w-4 h-4" />
- )}
- <span>{conn!.displayName}</span>
- </div>
- );
- }}
- />
- <FormMessage />
- </div>
- )}
- />
- )}
- </>
- )}
-
- <DialogFooter>
- <DialogClose asChild>
- <Button type="button" variant="ghost">
- {t('Cancel')}
- </Button>
- </DialogClose>
- <Button type="submit" loading={isFetchingAffectedFlows}>
- {t('Next')}
- </Button>
- </DialogFooter>
- </form>
- </Form>
- ) : (
- <div className="flex flex-col gap-4">
- {affectedFlows.length === 0 ? (
- <div className="flex items-center gap-2 rounded-md border border-dashed px-3 py-2.5 text-sm text-gray-11">
- <WorkflowIcon className="w-4 h-4 shrink-0" />
- {t('No flows use this connection yet')}
- </div>
- ) : (
- <Collapsible defaultOpen className="rounded-md border">
- <CollapsibleTrigger className="group flex w-full items-center justify-between gap-2 px-3 py-2.5 text-sm font-medium">
- <span>
- {t('flowsUsingConnection', { count: affectedFlows.length })}
- </span>
- <ChevronDown className="w-4 h-4 shrink-0 text-gray-11 transition-transform group-data-[state=closed]:-rotate-90" />
- </CollapsibleTrigger>
- <CollapsibleContent>
- <ScrollArea className="max-h-[140px] px-3 pb-3">
- <div className="flex flex-wrap gap-1.5">
- {affectedFlows.map((flow) => (
- <Badge
- key={flow.id}
- variant="secondary"
- className="max-w-[200px] cursor-pointer hover:bg-gray-3/70"
- onClick={() =>
- navigate(
- `/projects/${flow.projectId}/flows/${flow.id}`,
- )
- }
- >
- <WorkflowIcon className="w-3 h-3 shrink-0" />
- <span className="truncate">
- {flow.version.displayName}
- </span>
- </Badge>
- ))}
- </div>
- </ScrollArea>
- </CollapsibleContent>
- </Collapsible>
- )}
-
- <div className="flex flex-col gap-1.5">
- <LabelWithTooltip
- label={t('Which versions to update')}
- tooltip={t(
- '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.',
- )}
- />
- <Select
- value={versionScope}
- onValueChange={(value) =>
- setVersionScope(value as VersionScope)
- }
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="draft">{t('Draft only')}</SelectItem>
- <SelectItem value="published">
- {t('Draft and published')}
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
-
- <span className="text-xs text-gray-11">
- {t(
- 'MCP servers are not updated automatically — reconnect them manually.',
- )}
- </span>
-
- <DialogFooter>
- <Button type="button" variant="secondary" onClick={handleBack}>
- {t('Back')}
- </Button>
- <Button
- type="button"
- onClick={() => handleConfirmedSubmit(form.getValues())}
- loading={isReplacing}
- disabled={affectedFlows.length === 0}
- >
- {t('Replace')}
- </Button>
- </DialogFooter>
- </div>
- )}
- </DialogContent>
- </Dialog>
- );
-};
-
-function LabelWithTooltip({
- label,
- tooltip,
-}: {
- label: string;
- tooltip: string;
-}) {
- return (
- <div className="flex items-center gap-1.5">
- <Label>{label}</Label>
- <Tooltip>
- <TooltipTrigger asChild>
- <Info className="w-3.5 h-3.5 text-gray-11 cursor-help" />
- </TooltipTrigger>
- <TooltipContent className="max-w-xs">{tooltip}</TooltipContent>
- </Tooltip>
- </div>
- );
-}
-
-ReplaceConnectionsDialog.displayName = 'ReplaceConnectionsDialog';
-export { ReplaceConnectionsDialog };
diff --git a/packages/web/src/app/routes/connections/index.tsx b/packages/web/src/app/routes/connections/index.tsx
index ef6d2bd07a9..48d9b261523 100644
--- a/packages/web/src/app/routes/connections/index.tsx
+++ b/packages/web/src/app/routes/connections/index.tsx
@@ -19,9 +19,10 @@ import {
import { useMemo, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
+import { DeleteConnectionsDialog } from '@/app/connections/delete-connections-dialog';
import { NewConnectionDialog } from '@/app/connections/new-connection-dialog';
import { ReconnectButtonDialog } from '@/app/connections/reconnect-button-dialog';
-import { ReplaceConnectionsDialog } from '@/app/connections/replace-connections-dialog';
+import { ReplaceConnectionForProjectDialog } from '@/app/connections/replace-connection-for-project-dialog';
import { AnimatedIconButton } from '@/components/custom/animated-icon-button';
import { CopyTextTooltip } from '@/components/custom/clipboard/copy-text-tooltip';
import {
@@ -33,9 +34,7 @@ import {
RowDataWithActions,
} from '@/components/custom/data-table';
import { DataTableColumnHeader } from '@/components/custom/data-table/data-table-column-header';
-import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';
import { FormattedDate } from '@/components/custom/formatted-date';
-import { DeleteConnectionWarning } from '@/components/custom/global-connection-utils';
import { PermissionNeededTooltip } from '@/components/custom/permission-needed-tooltip';
import { StatusIconWithText } from '@/components/custom/status-icon-with-text';
import { TextWithTooltip } from '@/components/custom/text-with-tooltip';
@@ -354,23 +353,20 @@ function AppConnectionsPage() {
return (
<>
{deletableRows.length > 0 && (
- <ConfirmationDeleteDialog
+ <DeleteConnectionsDialog
+ connections={deletableRows}
title={t('Delete Connections')}
message={t(
'The selected connections will be permanently deleted.',
)}
- warning={<DeleteConnectionWarning />}
mutationFn={async () => {
await deleteConnections(deletableRows.map((row) => row.id));
refetch();
resetSelection();
setSelectedRows([]);
}}
- entityName={t('connection')}
- buttonText={t('Delete')}
open={showDeleteDialog}
onOpenChange={setShowDeleteDialog}
- showToast
>
<Button
variant="ghost"
@@ -381,7 +377,7 @@ function AppConnectionsPage() {
<Trash2 className="h-4 w-4 mr-1" />
{t('Delete')} ({deletableRows.length})
</Button>
- </ConfirmationDeleteDialog>
+ </DeleteConnectionsDialog>
)}
</>
);
@@ -397,7 +393,7 @@ function AppConnectionsPage() {
key="replace"
hasPermission={userHasPermissionToWriteAppConnection}
>
- <ReplaceConnectionsDialog
+ <ReplaceConnectionForProjectDialog
projectId={projectId}
onConnectionMerged={() => {
setRefresh(refresh + 1);
@@ -412,7 +408,7 @@ function AppConnectionsPage() {
>
{t('Replace')}
</AnimatedIconButton>
- </ReplaceConnectionsDialog>
+ </ReplaceConnectionForProjectDialog>
</PermissionNeededTooltip>,
<PermissionNeededTooltip
key="new"
diff --git a/packages/web/src/app/routes/platform/setup/connections/index.tsx b/packages/web/src/app/routes/platform/setup/connections/index.tsx
index e2bc6920b68..f1814c6fed2 100644
--- a/packages/web/src/app/routes/platform/setup/connections/index.tsx
+++ b/packages/web/src/app/routes/platform/setup/connections/index.tsx
@@ -26,6 +26,7 @@ import {
StatusTone,
adminPageResources,
} from '@/app/components/admin';
+import { DeleteConnectionsDialog } from '@/app/connections/delete-connections-dialog';
import { NewConnectionDialog } from '@/app/connections/new-connection-dialog';
import { ReconnectButtonDialog } from '@/app/connections/reconnect-button-dialog';
import { AnimatedIconButton } from '@/components/custom/animated-icon-button';
@@ -38,12 +39,8 @@ import {
RowDataWithActions,
} from '@/components/custom/data-table';
import { DataTableColumnHeader } from '@/components/custom/data-table/data-table-column-header';
-import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';
import { FormattedDate } from '@/components/custom/formatted-date';
-import {
- DefaultTag,
- DeleteConnectionWarning,
-} from '@/components/custom/global-connection-utils';
+import { DefaultTag } from '@/components/custom/global-connection-utils';
import { PlusIcon } from '@/components/icons/plus';
import { Button } from '@/components/ui/button';
import {
@@ -87,6 +84,7 @@ const GlobalConnectionsTable = () => {
const [selectedRows, setSelectedRows] = useState<
Array<AppConnectionWithoutSensitiveData>
>([]);
+ const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const { checkAccess } = useAuthorization();
const location = useLocation();
@@ -247,14 +245,14 @@ const GlobalConnectionsTable = () => {
) => {
return (
<div onClick={(e) => e.stopPropagation()}>
- <ConfirmationDeleteDialog
+ <DeleteConnectionsDialog
+ connections={selectedRows}
title={t('Delete Connections')}
message={t(
'The selected connections will be permanently deleted.',
)}
- warning={<DeleteConnectionWarning />}
- entityName="connections"
- buttonText={t('Delete')}
+ open={showDeleteDialog}
+ onOpenChange={setShowDeleteDialog}
controlId={AdminControl.CONNECTIONS_CONNECTION_DELETE_CONFIRM}
mutationFn={async () => {
try {
@@ -282,13 +280,13 @@ const GlobalConnectionsTable = () => {
{`${t('Delete')} (${selectedRows.length})`}
</Button>
)}
- </ConfirmationDeleteDialog>
+ </DeleteConnectionsDialog>
</div>
);
},
},
],
- [bulkDeleteGlobalConnections, selectedRows],
+ [bulkDeleteGlobalConnections, selectedRows, showDeleteDialog],
);
return (
diff --git a/packages/web/src/components/ui/label.tsx b/packages/web/src/components/ui/label.tsx
index cc510e3d59a..24e56f27628 100644
--- a/packages/web/src/components/ui/label.tsx
+++ b/packages/web/src/components/ui/label.tsx
@@ -1,6 +1,12 @@
+import { Info } from 'lucide-react';
import { Label as LabelPrimitive } from 'radix-ui';
import * as React from 'react';
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
type LabelProps = React.ComponentProps<typeof LabelPrimitive.Root> & {
@@ -32,5 +38,25 @@ function Label({
);
}
-export { Label, RequiredFieldAsterisk };
+function LabelWithTooltip({
+ label,
+ tooltip,
+}: {
+ label: string;
+ tooltip: string;
+}) {
+ return (
+ <div className="flex items-center gap-1.5">
+ <Label>{label}</Label>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Info className="w-3.5 h-3.5 text-gray-11 cursor-help" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs">{tooltip}</TooltipContent>
+ </Tooltip>
+ </div>
+ );
+}
+
+export { Label, LabelWithTooltip, RequiredFieldAsterisk };
export type { LabelProps };
diff --git a/packages/web/src/features/connections/hooks/app-connections-hooks.ts b/packages/web/src/features/connections/hooks/app-connections-hooks.ts
index 0b746667497..815f9c4c675 100644
--- a/packages/web/src/features/connections/hooks/app-connections-hooks.ts
+++ b/packages/web/src/features/connections/hooks/app-connections-hooks.ts
@@ -3,6 +3,7 @@ import {
ErrorCode,
isNil,
SeekPage,
+ unique,
} from '@activepieces/core-utils';
import {
getAuthPropertyForValue,
@@ -12,6 +13,7 @@ import {
AppConnectionScope,
AppConnectionStatus,
AppConnectionWithoutSensitiveData,
+ FlowVersionState,
ListAppConnectionsRequestQuery,
PLACEHOLDER_CONNECTION_TYPE,
ReplaceAppConnectionsRequestBody,
@@ -30,6 +32,9 @@ import {
} from '@/components/custom/data-table';
import { useEmbedding } from '@/components/providers/embed-provider';
import { internalErrorToast } from '@/components/ui/sonner';
+import { agentsApi } from '@/features/agents/api/agents';
+import { useAgentsAvailable } from '@/features/agents/hooks/agents-hooks';
+import { flowsApi } from '@/features/flows/api/flows-api';
import { projectMembersApi } from '@/features/members/api/project-members-api';
import { api } from '@/lib/api';
import { authenticationSession } from '@/lib/authentication-session';
@@ -45,6 +50,7 @@ import {
type UseReplaceConnectionsProps = {
setDialogOpen: (isOpen: boolean) => void;
refetch: () => void;
+ connections: AppConnectionWithoutSensitiveData[];
};
type UseRenameAppConnectionProps = {
@@ -301,14 +307,24 @@ export const appConnectionsMutations = {
useReplaceConnections: ({
setDialogOpen,
refetch,
+ connections,
}: UseReplaceConnectionsProps) => {
return useMutation({
mutationFn: async (request: ReplaceAppConnectionsRequestBody) => {
await appConnectionsApi.replace(request);
},
- onSuccess: () => {
+ onSuccess: (_, request) => {
+ const displayNameOf = (id: string) =>
+ connections.find((connection) => connection.id === id)?.displayName ??
+ id;
toast.success(t('Success'), {
- description: t('Connections replaced successfully'),
+ description: t(
+ 'Replaced connection {sourceName} with connection {targetName}',
+ {
+ sourceName: displayNameOf(request.sourceAppConnectionId),
+ targetName: displayNameOf(request.targetAppConnectionId),
+ },
+ ),
});
setDialogOpen(false);
refetch();
@@ -377,6 +393,27 @@ export const appConnectionsQueries = {
});
},
+ useFlowsAndAgentsUsingConnections: ({
+ connections,
+ enabled,
+ }: {
+ connections: ConnectionToCheck[];
+ enabled: boolean;
+ }) => {
+ const agentsAvailable = useAgentsAvailable();
+ return useQuery({
+ queryKey: ['app-connection-usage', connections, agentsAvailable],
+ queryFn: () =>
+ listFlowsAndAgentsUsingConnections({
+ connections,
+ agentsAvailable,
+ }),
+ enabled,
+ staleTime: 0,
+ gcTime: 0,
+ });
+ },
+
useListSearchParams: () => {
const { search } = useLocation();
return useMemo(() => {
@@ -422,3 +459,74 @@ export const appConnectionsQueries = {
});
},
};
+
+async function listFlowsAndAgentsUsingConnections({
+ connections,
+ agentsAvailable,
+}: {
+ connections: ConnectionToCheck[];
+ agentsAvailable: boolean;
+}) {
+ const projectIds = unique(
+ connections.flatMap((connection) => connection.projectIds),
+ );
+ const usagePerProject = await Promise.all(
+ projectIds.map((projectId) =>
+ listFlowsAndAgentsUsingConnectionsInProject({
+ projectId,
+ externalIds: connections
+ .filter((connection) => connection.projectIds.includes(projectId))
+ .map((connection) => connection.externalId),
+ agentsAvailable,
+ }),
+ ),
+ );
+ return {
+ flows: usagePerProject.flatMap((usage) => usage.flows),
+ agents: usagePerProject.flatMap((usage) => usage.agents),
+ };
+}
+
+async function listFlowsAndAgentsUsingConnectionsInProject({
+ projectId,
+ externalIds,
+ agentsAvailable,
+}: {
+ projectId: string;
+ externalIds: string[];
+ agentsAvailable: boolean;
+}) {
+ const flowsRequest = {
+ projectId,
+ connectionExternalIds: externalIds,
+ cursor: undefined,
+ limit: 1000,
+ };
+ const [draftFlowsPage, publishedFlowsPage, agentsPage] = await Promise.all([
+ flowsApi.list(flowsRequest),
+ flowsApi.list({
+ ...flowsRequest,
+ versionState: FlowVersionState.LOCKED,
+ }),
+ agentsAvailable
+ ? agentsApi.list({
+ projectId,
+ connectionExternalIds: externalIds,
+ limit: 100,
+ })
+ : null,
+ ]);
+ const draftFlowIds = new Set(draftFlowsPage.data.map((flow) => flow.id));
+ return {
+ flows: [
+ ...draftFlowsPage.data,
+ ...publishedFlowsPage.data.filter((flow) => !draftFlowIds.has(flow.id)),
+ ],
+ agents: agentsPage?.data ?? [],
+ };
+}
+
+type ConnectionToCheck = Pick<
+ AppConnectionWithoutSensitiveData,
+ 'externalId' | 'projectIds'
+>;
diff --git a/packages/web/src/features/flow-approvals/hooks/flow-approvals-hooks.ts b/packages/web/src/features/flow-approvals/hooks/flow-approvals-hooks.ts
index 35ac7813c31..d4ca8f5d52f 100644
--- a/packages/web/src/features/flow-approvals/hooks/flow-approvals-hooks.ts
+++ b/packages/web/src/features/flow-approvals/hooks/flow-approvals-hooks.ts
@@ -18,6 +18,16 @@ import { flowApprovalsApi } from '../api/flow-approvals-api';
const PENDING_BADGE_PROBE_LIMIT = 11;
export const flowApprovalsHooks = {
+ usePublishNeedsApproval: (): boolean => {
+ const { platform } = platformHooks.useCurrentPlatform();
+ const { project } = projectCollectionUtils.useCurrentProject();
+ const { checkAccess } = useAuthorization();
+ return (
+ platform.plan.environmentsEnabled &&
+ !!project.sensitive &&
+ !checkAccess(Permission.PUBLISH_SENSITIVE_FLOW_ACCESS)
+ );
+ },
useListApprovals: ({
cursor,
limit,
diff --git a/packages/web/src/features/flows/hooks/flow-hooks.tsx b/packages/web/src/features/flows/hooks/flow-hooks.tsx
index 0c96171f4a9..13adeb289e8 100644
--- a/packages/web/src/features/flows/hooks/flow-hooks.tsx
+++ b/packages/web/src/features/flows/hooks/flow-hooks.tsx
@@ -11,6 +11,7 @@ import {
FlowStatus,
FlowVersion,
FlowVersionMetadata,
+ FlowVersionState,
FlowVersionTemplate,
ListFlowsRequest,
PopulatedFlow,
@@ -595,6 +596,43 @@ export const flowHooks = {
onError,
});
},
+ useListFlowsUsingConnection: ({
+ projectId,
+ onSuccess,
+ }: {
+ projectId: string;
+ onSuccess: () => void;
+ }) => {
+ return useMutation({
+ mutationFn: async (externalId: string) => {
+ const request = {
+ projectId,
+ connectionExternalIds: [externalId],
+ cursor: undefined,
+ limit: FLOWS_PAGE_SIZE,
+ };
+ const [draftFlows, publishedFlows] = await Promise.all([
+ listAllFlows(request),
+ listAllFlows({ ...request, versionState: FlowVersionState.LOCKED }),
+ ]);
+ const draftFlowIds = new Set(draftFlows.map((flow) => flow.id));
+ return {
+ draftFlows,
+ publishedOnlyFlows: publishedFlows.filter(
+ (flow) => !draftFlowIds.has(flow.id),
+ ),
+ draftFlowIds,
+ publishedFlowIds: new Set(publishedFlows.map((flow) => flow.id)),
+ };
+ },
+ onSuccess,
+ onError: () => {
+ toast.error(t('Error'), {
+ description: t('Failed to get affected flows'),
+ });
+ },
+ });
+ },
createFlowQueryKeys: ({
flowId,
versionId,
@@ -624,6 +662,22 @@ export const flowHooks = {
},
};
+async function listAllFlows(
+ request: ListFlowsRequest,
+): Promise<PopulatedFlow[]> {
+ const flows: PopulatedFlow[] = [];
+ let cursor: string | undefined = undefined;
+ do {
+ const page: SeekPage<PopulatedFlow> = await flowsApi.list({
+ ...request,
+ cursor,
+ });
+ flows.push(...page.data);
+ cursor = page.next ?? undefined;
+ } while (cursor);
+ return flows;
+}
+
type UseChangeFlowStatusParams = {
flowId: string;
change: 'publish' | FlowStatus;
@@ -633,3 +687,5 @@ type UseChangeFlowStatusParams = {
params: RequiredActionsMissingErrorParams['params'],
) => void;
};
+
+const FLOWS_PAGE_SIZE = 1000;