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(builder): confirm before a connection switch clears a step's inputs (#17132)

Abdula44a76eebfe2
diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.json
index 45feb032515..0229dda3ad5 100644
--- a/packages/web/public/locales/en/translation.json
+++ b/packages/web/public/locales/en/translation.json
@@ -3724,5 +3724,9 @@
"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."
+ "Replace in all steps": "Replace in all steps",
+ "Switch": "Switch",
+ "{flowCount, plural, =1 {We recommend testing the flow after the replace. If {newName} can't access the same data as {oldName}, the flow could break.} other {We recommend testing these flows after the replace. If {newName} can't access the same data as {oldName}, they could break.}}": "{flowCount, plural, =1 {We recommend testing the flow after the replace. If {newName} can't access the same data as {oldName}, the flow could break.} other {We recommend testing these flows after the replace. If {newName} can't access the same data as {oldName}, they could break.}}",
+ "Switching can clear {inputs} in this step's settings, if the {newConnectionDisplayName} connection doesn't have access to them.": "Switching can clear {inputs} in this step's settings, if the {newConnectionDisplayName} connection doesn't have access to them.",
+ "Switch to {newConnectionDisplayName}?": "Switch to {newConnectionDisplayName}?"
}
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.tsx
index 2c574fdc3db..bb3b1602362 100644
--- a/packages/web/src/app/builder/builder-header/flow-connections-popover.tsx
+++ b/packages/web/src/app/builder/builder-header/flow-connections-popover.tsx
@@ -1,13 +1,12 @@
-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 { DataFetchErrorState } from '@/components/custom/data-fetch-error-state';
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,
@@ -18,8 +17,8 @@ import {
PopoverTrigger,
} from '@/components/ui/popover';
import { ScrollArea } from '@/components/ui/scroll-area';
+import { appConnectionsHooks } from '@/features/connections';
import { PieceIconWithPieceName } from '@/features/pieces';
-import { useAuthorization } from '@/hooks/authorization-hooks';
import { ReplaceConnectionForFlowDialog } from './replace-connection-for-flow-dialog';
@@ -28,16 +27,15 @@ export const FlowConnectionsPopover = ({
}: {
isFlowLocked: boolean;
}) => {
- const { flowConnections } = flowCanvasHooks.useFlowConnections();
- const showReplace = !useEmbedding().embedState.hideReplaceConnection;
- const hasPermissionToReplace = useAuthorization().checkAccess(
- Permission.REPLACE_APP_CONNECTION,
- );
+ const { flowConnections, isError, refetch } =
+ flowCanvasHooks.useFlowConnections();
+ const { showReplace, hasPermissionToReplace } =
+ appConnectionsHooks.useReplaceConnectionAccess();
const [popoverOpen, setPopoverOpen] = useState(false);
const [connectionToReplace, setConnectionToReplace] =
useState<AppConnectionWithoutSensitiveData | null>(null);
- if (flowConnections.length === 0) {
+ if (flowConnections.length === 0 && !isError) {
return null;
}
@@ -48,7 +46,9 @@ export const FlowConnectionsPopover = ({
<Button variant="ghost">
<Plug className="w-4 h-4" />
{t('Connections')}
- <span className="text-gray-11">{flowConnections.length}</span>
+ {!isError && (
+ <span className="text-gray-11">{flowConnections.length}</span>
+ )}
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-[340px] p-0">
@@ -60,49 +60,57 @@ export const FlowConnectionsPopover = ({
</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);
- }}
+ {isError ? (
+ <DataFetchErrorState
+ entity={t('connections')}
+ onRetry={refetch}
+ className="py-6"
+ />
+ ) : (
+ <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}
>
- {t('Replace')}
- </Button>
- </PermissionNeededTooltip>
- )}
- </div>
- ))}
- </div>
- </ScrollArea>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={!hasPermissionToReplace || isFlowLocked}
+ onClick={() => {
+ setPopoverOpen(false);
+ setConnectionToReplace(connection);
+ }}
+ >
+ {t('Replace')}
+ </Button>
+ </PermissionNeededTooltip>
+ )}
+ </div>
+ ))}
+ </div>
+ </ScrollArea>
+ )}
</PopoverContent>
</Popover>
{connectionToReplace && (
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
index a4b4e2f4886..fa8759ba9b7 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,18 +1,17 @@
import { AppConnectionWithoutSensitiveData } from '@activepieces/shared';
import { useMutation } from '@tanstack/react-query';
import { t } from 'i18next';
-import { Info } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { useBuilderStateContext } from '@/app/builder/builder-hooks';
import { flowCanvasHooks } from '@/app/builder/flow-canvas/hooks';
import {
- ReplaceConnectionSelection,
+ ReplaceConnectionFlowVersionsField,
+ ReplaceConnectionFlowVersionsSelection,
ReplaceConnectionSelectionFields,
- replaceConnectionSelectionUtils,
- ReplaceConnectionVersionsField,
+ ReplaceConnectionSourceKind,
+ ReplaceConnectionTestFlowsAlert,
} from '@/app/connections/replace-connection-selection-form';
-import { Alert, AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import {
Dialog,
@@ -34,6 +33,7 @@ import { authenticationSession } from '@/lib/authentication-session';
const ReplaceConnectionForFlowDialog = ({
sourceConnection,
+ targetConnection,
open,
onOpenChange,
}: ReplaceConnectionForFlowDialogProps) => {
@@ -59,6 +59,7 @@ const ReplaceConnectionForFlowDialog = ({
<ReplaceConnectionForFlowForm
key={open ? 'open' : 'closed'}
sourceConnection={sourceConnection}
+ targetConnection={targetConnection}
setDialogOpen={onOpenChange}
/>
</DialogContent>
@@ -68,9 +69,11 @@ const ReplaceConnectionForFlowDialog = ({
function ReplaceConnectionForFlowForm({
sourceConnection,
+ targetConnection,
setDialogOpen,
}: {
sourceConnection: AppConnectionWithoutSensitiveData;
+ targetConnection?: AppConnectionWithoutSensitiveData;
setDialogOpen: (open: boolean) => void;
}) {
const [flow, savePendingEdits, showsNewestVersion] = useBuilderStateContext(
@@ -103,16 +106,14 @@ function ReplaceConnectionForFlowForm({
replaceConnections({
flowIds: [flow.id],
projectId,
- sourceAppConnectionId: values.sourceConnectionId,
+ sourceAppConnectionId: sourceConnection.id,
targetAppConnectionId: values.targetConnectionId,
applyToPublishedVersions: values.applyToPublishedVersions,
}),
});
const form = useForm<FlowReplaceFormValues>({
defaultValues: {
- ...replaceConnectionSelectionUtils.emptySelection(),
- pieceName: sourceConnection.pieceName,
- sourceConnectionId: sourceConnection.id,
+ targetConnectionId: targetConnection?.id ?? '',
applyToPublishedVersions: false,
},
mode: 'onSubmit',
@@ -125,21 +126,19 @@ function ReplaceConnectionForFlowForm({
onSubmit={form.handleSubmit((values) => saveEditsThenReplace(values))}
className="flex flex-col gap-4"
>
- <Alert>
- <Info className="size-4" />
- <AlertDescription>
- {t(
- 'Test the flow after the replace to make sure every step still works.',
- )}
- </AlertDescription>
- </Alert>
- <ReplaceConnectionVersionsField />
+ <ReplaceConnectionFlowVersionsField />
<ReplaceConnectionSelectionFields
- pieces={[]}
- sourceConnections={[sourceConnection]}
+ source={{
+ kind: ReplaceConnectionSourceKind.FIXED,
+ connection: sourceConnection,
+ }}
targetConnections={projectConnections}
loading={connectionsLoading}
- hideSourceFields
+ />
+ <ReplaceConnectionTestFlowsAlert
+ sourceConnection={sourceConnection}
+ targetConnections={projectConnections}
+ flowCount={1}
/>
<DialogFooter>
<DialogClose asChild>
@@ -159,12 +158,13 @@ function ReplaceConnectionForFlowForm({
ReplaceConnectionForFlowDialog.displayName = 'ReplaceConnectionForFlowDialog';
export { ReplaceConnectionForFlowDialog };
-type FlowReplaceFormValues = ReplaceConnectionSelection & {
- applyToPublishedVersions: boolean;
+type FlowReplaceFormValues = ReplaceConnectionFlowVersionsSelection & {
+ targetConnectionId: string;
};
type ReplaceConnectionForFlowDialogProps = {
sourceConnection: AppConnectionWithoutSensitiveData;
+ targetConnection?: 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.tsx
index 56c703557d6..4e94cdb646e 100644
--- a/packages/web/src/app/builder/flow-canvas/hooks.tsx
+++ b/packages/web/src/app/builder/flow-canvas/hooks.tsx
@@ -327,16 +327,21 @@ function isActiveElementInsideListMapperModeInput(): boolean {
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 {
+ data: connections,
+ isLoading,
+ isError,
+ refetch,
+ } = 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 ?? [])
+ const projectConnections = connections?.data ?? [];
+ const flowConnections = projectConnections
.map((connection) => ({
connection,
stepCount: stepConnectionExternalIds.filter((connectionExternalIds) =>
@@ -344,7 +349,7 @@ const useFlowConnections = () => {
).length,
}))
.filter(({ stepCount }) => stepCount > 0);
- return { flowConnections, isLoading };
+ return { flowConnections, projectConnections, isLoading, isError, refetch };
};
export const flowCanvasHooks = {
diff --git a/packages/web/src/app/builder/piece-properties/dynamic-piece-property.tsx b/packages/web/src/app/builder/piece-properties/dynamic-piece-property.tsx
index 6d697876897..73b73cb51fa 100644
--- a/packages/web/src/app/builder/piece-properties/dynamic-piece-property.tsx
+++ b/packages/web/src/app/builder/piece-properties/dynamic-piece-property.tsx
@@ -119,7 +119,7 @@ const DynamicPropertiesImplementation = React.memo(
prefix: propertyPrefix,
});
const currentValue = form.getValues(propertyPath);
- if (!isNil(currentValue)) {
+ if (!isNil(currentValue) && Object.keys(currentValue).length > 0) {
lastKnownValue.current = { ...currentValue };
}
if (!deepEqual(previousRefresherValues.current, refresherValues)) {
diff --git a/packages/web/src/app/builder/step-settings/piece-settings/index.tsx b/packages/web/src/app/builder/step-settings/piece-settings/index.tsx
index ed9d8c2eddf..d7f601b5035 100644
--- a/packages/web/src/app/builder/step-settings/piece-settings/index.tsx
+++ b/packages/web/src/app/builder/step-settings/piece-settings/index.tsx
@@ -16,7 +16,6 @@ import React from 'react';
import { useFormContext } from 'react-hook-form';
import { AutoFormFieldWrapper } from '@/app/builder/piece-properties/auto-form-field-wrapper';
-import { ConnectionSelect } from '@/app/connections/connection-select';
import { FormField } from '@/components/ui/form';
import { Skeleton } from '@/components/ui/skeleton';
import { flagsHooks } from '@/hooks/flags-hooks';
@@ -28,6 +27,8 @@ import { GenericPropertiesForm } from '../../piece-properties/generic-properties
import { PieceNotAvailableAlert } from '../piece-not-available-alert';
import { useStepSettingsContext } from '../step-settings-context';
+import { ConnectionSelectWithSwitchConfirmation } from './switch-connection-confirmation-dialog';
+
const PieceSettings = React.memo((props: PieceSettingsProps) => {
const {
pieceModel,
@@ -174,8 +175,9 @@ const PieceSettings = React.memo((props: PieceSettingsProps) => {
dynamicInputModeToggled={authDynamicInputModeToggled}
isForConnectionSelect={true}
>
- <ConnectionSelect
+ <ConnectionSelectWithSwitchConfirmation
piece={pieceModel}
+ stepProps={(selectedAction ?? selectedTrigger)?.props ?? {}}
value={field.value}
onChange={field.onChange}
disabled={props.readonly}
diff --git a/packages/web/src/app/builder/step-settings/piece-settings/switch-connection-confirmation-dialog.tsx b/packages/web/src/app/builder/step-settings/piece-settings/switch-connection-confirmation-dialog.tsx
new file mode 100644
index 00000000000..3a0412f9705
--- /dev/null
+++ b/packages/web/src/app/builder/step-settings/piece-settings/switch-connection-confirmation-dialog.tsx
@@ -0,0 +1,317 @@
+import {
+ connectionTemplate,
+ isEmpty,
+ isNil,
+ isObject,
+} from '@activepieces/core-utils';
+import {
+ PieceMetadataModel,
+ PieceMetadataModelSummary,
+ PiecePropertyMap,
+ PropertyType,
+} from '@activepieces/pieces-framework';
+import {
+ AppConnectionWithoutSensitiveData,
+ PieceAction,
+ PieceTrigger,
+ PropertyExecutionType,
+ PropertySettings,
+} from '@activepieces/shared';
+import i18next, { t } from 'i18next';
+import { useState } from 'react';
+import { useFormContext } from 'react-hook-form';
+
+import { ReplaceConnectionForFlowDialog } from '@/app/builder/builder-header/replace-connection-for-flow-dialog';
+import { ConnectionSelect } from '@/app/connections/connection-select';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import {
+ appConnectionsHooks,
+ appConnectionsQueries,
+} from '@/features/connections';
+import { authenticationSession } from '@/lib/authentication-session';
+
+export function ConnectionSelectWithSwitchConfirmation({
+ piece,
+ stepProps,
+ value,
+ onChange,
+ disabled,
+}: ConnectionSelectWithSwitchConfirmationProps) {
+ const form = useFormContext<PieceAction | PieceTrigger>();
+ const projectId = authenticationSession.getProjectId()!;
+ const { data: pieceConnections } = appConnectionsQueries.useAppConnections({
+ request: { pieceName: piece.name, projectId, limit: 1000 },
+ pieceAuth: piece.auth,
+ extraKeys: [piece.name, projectId],
+ staleTime: 0,
+ });
+ const { showReplace, hasPermissionToReplace } =
+ appConnectionsHooks.useReplaceConnectionAccess();
+ const [pendingSwitch, setPendingSwitch] = useState<PendingSwitch | null>(
+ null,
+ );
+ const [connectionsToReplace, setConnectionsToReplace] =
+ useState<ConnectionsToReplace | null>(null);
+
+ const findConnection = (connectionValue: string | undefined) =>
+ pieceConnections?.data.find(
+ (connection) =>
+ connection.externalId ===
+ connectionTemplate.unwrapExternalId(connectionValue),
+ );
+
+ const handleChange = (newValue: string) => {
+ const currentExternalId = connectionTemplate.unwrapExternalId(value);
+ const isSwitch =
+ !isNil(currentExternalId) &&
+ currentExternalId !== connectionTemplate.unwrapExternalId(newValue);
+ if (!isSwitch) {
+ onChange(newValue);
+ return;
+ }
+ const { settings } = form.getValues();
+ const clearedInputs = listInputsClearedBySwitch({
+ props: stepProps,
+ input: settings.input,
+ propertySettings: settings.propertySettings,
+ });
+ if (clearedInputs.length === 0) {
+ onChange(newValue);
+ return;
+ }
+ setPendingSwitch({ newValue, clearedInputs });
+ };
+
+ const sourceConnection = findConnection(value);
+ const targetConnection = pendingSwitch
+ ? findConnection(pendingSwitch.newValue)
+ : undefined;
+ const canReplace =
+ showReplace && hasPermissionToReplace && !isNil(sourceConnection);
+
+ return (
+ <>
+ <ConnectionSelect
+ piece={piece}
+ value={value}
+ onChange={handleChange}
+ disabled={disabled}
+ />
+ {pendingSwitch && (
+ <SwitchConnectionConfirmationDialog
+ newConnectionDisplayName={targetConnection?.displayName ?? ''}
+ clearedInputs={pendingSwitch.clearedInputs}
+ onReplace={
+ canReplace && sourceConnection
+ ? () => {
+ setPendingSwitch(null);
+ setConnectionsToReplace({
+ source: sourceConnection,
+ target: targetConnection,
+ });
+ }
+ : undefined
+ }
+ onCancel={() => setPendingSwitch(null)}
+ onConfirm={() => {
+ setPendingSwitch(null);
+ onChange(pendingSwitch.newValue);
+ }}
+ />
+ )}
+ {connectionsToReplace && (
+ <ReplaceConnectionForFlowDialog
+ sourceConnection={connectionsToReplace.source}
+ targetConnection={connectionsToReplace.target}
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ setConnectionsToReplace(null);
+ }
+ }}
+ />
+ )}
+ </>
+ );
+}
+
+function SwitchConnectionConfirmationDialog({
+ newConnectionDisplayName,
+ clearedInputs,
+ onReplace,
+ onCancel,
+ onConfirm,
+}: SwitchConnectionConfirmationDialogProps) {
+ const [beforeInputs, afterInputs] = t(
+ "Switching can clear {inputs} in this step's settings, if the {newConnectionDisplayName} connection doesn't have access to them.",
+ { inputs: INPUTS_PLACEHOLDER, newConnectionDisplayName },
+ ).split(INPUTS_PLACEHOLDER);
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ onCancel();
+ }
+ }}
+ >
+ <DialogContent className="flex flex-col">
+ <DialogHeader>
+ <DialogTitle>
+ {t('Switch to {newConnectionDisplayName}?', {
+ newConnectionDisplayName,
+ })}
+ </DialogTitle>
+ </DialogHeader>
+ <DialogDescription className="text-gray-12">
+ {beforeInputs}
+ <InputNames names={clearedInputs.map((input) => input.displayName)} />
+ {afterInputs}
+ </DialogDescription>
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={onCancel}>
+ {t('Cancel')}
+ </Button>
+ {onReplace && (
+ <Button type="button" variant="outline" onClick={onReplace}>
+ {t('Replace in all steps')}
+ </Button>
+ )}
+ <Button type="button" onClick={onConfirm}>
+ {t('Switch')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function InputNames({ names }: { names: string[] }) {
+ const parts = new Intl.ListFormat(i18next.language, {
+ type: 'conjunction',
+ }).formatToParts(names);
+ return parts.map((part, index) =>
+ part.type === 'element' ? (
+ <strong key={index} className="font-semibold text-gray-12">
+ {part.value}
+ </strong>
+ ) : (
+ part.value
+ ),
+ );
+}
+
+function listInputsClearedBySwitch({
+ props,
+ input,
+ propertySettings,
+}: ListInputsClearedBySwitchParams): ClearedInput[] {
+ return Object.entries(props).flatMap(([propertyName, property]) => {
+ if (
+ propertySettings[propertyName]?.type === PropertyExecutionType.DYNAMIC
+ ) {
+ return [];
+ }
+ switch (property.type) {
+ case PropertyType.DROPDOWN:
+ case PropertyType.MULTI_SELECT_DROPDOWN:
+ return !isEmpty(input[propertyName])
+ ? [
+ {
+ path: propertyName,
+ displayName: property.displayName,
+ },
+ ]
+ : [];
+ case PropertyType.DYNAMIC:
+ return listDynamicChildrenWithValues({
+ propertyName,
+ propertyDisplayName: property.displayName,
+ schema: propertySettings[propertyName]?.schema,
+ value: input[propertyName],
+ });
+ default:
+ return [];
+ }
+ });
+}
+
+function listDynamicChildrenWithValues({
+ propertyName,
+ propertyDisplayName,
+ schema,
+ value,
+}: {
+ propertyName: string;
+ propertyDisplayName: string;
+ schema: unknown;
+ value: unknown;
+}): ClearedInput[] {
+ if (!isObject(value)) {
+ return [];
+ }
+ if (!isObject(schema)) {
+ return Object.values(value).some((childValue) => !isEmpty(childValue))
+ ? [{ path: propertyName, displayName: propertyDisplayName }]
+ : [];
+ }
+ return Object.entries(schema).flatMap(([childName, child]) =>
+ !isEmpty(value[childName]) &&
+ isObject(child) &&
+ typeof child.displayName === 'string'
+ ? [
+ {
+ path: `${propertyName}.${childName}`,
+ displayName: child.displayName,
+ },
+ ]
+ : [],
+ );
+}
+
+const INPUTS_PLACEHOLDER = '\u0000inputs\u0000';
+
+type ConnectionSelectWithSwitchConfirmationProps = {
+ piece: PieceMetadataModelSummary | PieceMetadataModel;
+ stepProps: PiecePropertyMap;
+ value: string | undefined;
+ onChange: (value: string) => void;
+ disabled?: boolean;
+};
+
+type PendingSwitch = {
+ newValue: string;
+ clearedInputs: ClearedInput[];
+};
+
+type ConnectionsToReplace = {
+ source: AppConnectionWithoutSensitiveData;
+ target: AppConnectionWithoutSensitiveData | undefined;
+};
+
+type SwitchConnectionConfirmationDialogProps = {
+ newConnectionDisplayName: string;
+ clearedInputs: ClearedInput[];
+ onReplace: (() => void) | undefined;
+ onCancel: () => void;
+ onConfirm: () => void;
+};
+
+type ClearedInput = {
+ path: string;
+ displayName: string;
+};
+
+type ListInputsClearedBySwitchParams = {
+ props: PiecePropertyMap;
+ input: Record<string, unknown>;
+ propertySettings: Record<string, PropertySettings>;
+};
diff --git a/packages/web/src/app/connections/connection-select.tsx b/packages/web/src/app/connections/connection-select.tsx
index 235b005c543..99b68d581ae 100644
--- a/packages/web/src/app/connections/connection-select.tsx
+++ b/packages/web/src/app/connections/connection-select.tsx
@@ -78,6 +78,7 @@ export function ConnectionSelect({
const {
data: connections,
isLoading: isLoadingConnections,
+ isError: isConnectionsError,
refetch,
} = appConnectionsQueries.useAppConnections({
request: {
@@ -114,17 +115,22 @@ export function ConnectionSelect({
setConnectionDialogOpen(true);
};
- if (isLoadingConnections || !pieceWithCorrectVersion) {
+ if (isLoadingConnections || isConnectionsError || !pieceWithCorrectVersion) {
return (
<SearchableSelect
options={[]}
disabled={true}
loading={isLoadingConnections}
- placeholder={t('Select a connection')}
+ placeholder={
+ isConnectionsError
+ ? t("Couldn't load your connections.")
+ : t('Select a connection')
+ }
value={value}
onChange={() => {}}
showDeselect={false}
- showRefresh={false}
+ showRefresh={isConnectionsError}
+ onRefresh={() => refetch()}
/>
);
}
@@ -137,13 +143,13 @@ export function ConnectionSelect({
piece={pieceWithCorrectVersion}
key={`CreateOrEditConnectionDialog-open-${connectionDialogOpen}`}
open={connectionDialogOpen}
- setOpen={(open, connection) => {
+ setOpen={async (open, connection) => {
setConnectionDialogOpen(open);
const createdValue = connectionTemplate.wrapExternalId(
connection?.externalId,
);
if (!isNil(createdValue)) {
- refetch();
+ await refetch();
onChange(createdValue);
}
}}
@@ -152,7 +158,7 @@ export function ConnectionSelect({
key={value ?? ''}
open={selectConnectionOpen}
onOpenChange={setSelectConnectionOpen}
- defaultValue={value}
+ value={value ?? ''}
onValueChange={onChange}
disabled={disabled}
>
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
index 0033dbd86a7..17c75f25a81 100644
--- a/packages/web/src/app/connections/replace-connection-for-project-dialog.tsx
+++ b/packages/web/src/app/connections/replace-connection-for-project-dialog.tsx
@@ -31,10 +31,13 @@ import { piecesHooks } from '@/features/pieces';
import { useNewWindow } from '@/lib/navigation-utils';
import {
+ ReplaceConnectionFlowVersionsField,
+ ReplaceConnectionFlowVersionsSelection,
ReplaceConnectionSelection,
ReplaceConnectionSelectionFields,
replaceConnectionSelectionUtils,
- ReplaceConnectionVersionsField,
+ ReplaceConnectionSourceKind,
+ ReplaceConnectionTestFlowsAlert,
} from './replace-connection-selection-form';
const ReplaceConnectionForProjectDialog = ({
@@ -170,8 +173,11 @@ function ReplaceConnectionForProjectForm({
{step === ProjectReplaceStep.CHOOSE_CONNECTIONS ? (
<>
<ReplaceConnectionSelectionFields
- pieces={replaceablePieces}
- sourceConnections={projectConnections}
+ source={{
+ kind: ReplaceConnectionSourceKind.CHOOSE,
+ pieces: replaceablePieces,
+ connections: projectConnections,
+ }}
targetConnections={projectConnections}
loading={piecesLoading || connectionsLoading}
/>
@@ -244,7 +250,15 @@ function ReplaceConnectionForProjectForm({
</Collapsible>
)}
- <ReplaceConnectionVersionsField />
+ {affectedFlows.length > 0 && (
+ <ReplaceConnectionTestFlowsAlert
+ sourceConnection={sourceConnection}
+ targetConnections={projectConnections}
+ flowCount={affectedFlows.length}
+ />
+ )}
+
+ <ReplaceConnectionFlowVersionsField />
<span className="text-xs text-gray-11">
{t('A replace changes up to {max} flows.', {
@@ -315,9 +329,8 @@ type ReplaceConnectionForProjectFormProps = {
setDialogOpen: (open: boolean) => void;
};
-type ProjectReplaceFormValues = ReplaceConnectionSelection & {
- applyToPublishedVersions: boolean;
-};
+type ProjectReplaceFormValues = ReplaceConnectionSelection &
+ ReplaceConnectionFlowVersionsSelection;
enum ProjectReplaceStep {
CHOOSE_CONNECTIONS = 'CHOOSE_CONNECTIONS',
diff --git a/packages/web/src/app/connections/replace-connection-selection-form.tsx b/packages/web/src/app/connections/replace-connection-selection-form.tsx
index c0b22955f1b..c60886e1870 100644
--- a/packages/web/src/app/connections/replace-connection-selection-form.tsx
+++ b/packages/web/src/app/connections/replace-connection-selection-form.tsx
@@ -22,138 +22,162 @@ import { flowApprovalsHooks } from '@/features/flow-approvals';
import { PieceIconWithPieceName } from '@/features/pieces';
const ReplaceConnectionSelectionFields = ({
- pieces,
- sourceConnections,
+ source,
targetConnections,
loading,
- hideSourceFields = false,
}: ReplaceConnectionSelectionFieldsProps) => {
const form = useFormContext<ReplaceConnectionSelection>();
- const selectedPiece = useWatch({ control: form.control, name: 'pieceName' });
- const sourceConnectionId = useWatch({
+ const selectedPieceName = useWatch({
+ control: form.control,
+ name: 'pieceName',
+ });
+ const selectedSourceConnectionId = useWatch({
control: form.control,
name: 'sourceConnectionId',
});
-
- const pieceSourceConnections = sourceConnections.filter(
- (connection) => connection.pieceName === selectedPiece,
- );
+ const isSourceFixed = source.kind === ReplaceConnectionSourceKind.FIXED;
+ const pieceName = isSourceFixed
+ ? source.connection.pieceName
+ : selectedPieceName;
+ const sourceConnectionId = isSourceFixed
+ ? source.connection.id
+ : selectedSourceConnectionId;
const pieceTargetConnections = targetConnections.filter(
(connection) =>
- connection.pieceName === selectedPiece &&
+ connection.pieceName === pieceName &&
connection.id !== sourceConnectionId,
);
return (
<>
- {!hideSourceFields && (
+ {source.kind === ReplaceConnectionSourceKind.CHOOSE && (
+ <SourceSelectionFields
+ pieces={source.pieces}
+ connections={source.connections}
+ loading={loading}
+ />
+ )}
+ {pieceName && (
<FormField
control={form.control}
- name="pieceName"
- rules={{ required: t('Please select a piece') }}
+ name="targetConnectionId"
+ rules={{
+ required: t('Please select a connection to replace with'),
+ }}
render={({ field }) => (
<div className="flex flex-col gap-2">
- <Label>{t('Piece')}</Label>
+ <Label>{t('Replace with')}</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>
- );
- }}
+ 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>
)}
/>
)}
+ </>
+ );
+};
- {selectedPiece && (
- <>
- {!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,
- )}
- />
+function SourceSelectionFields({
+ pieces,
+ connections,
+ loading,
+}: SourceSelectionFieldsProps) {
+ const form = useFormContext<ReplaceConnectionSelection>();
+ const selectedPieceName = useWatch({
+ control: form.control,
+ name: 'pieceName',
+ });
+ const pieceConnections = connections.filter(
+ (connection) => connection.pieceName === selectedPieceName,
+ );
+ 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>
+ )}
+ />
+ {selectedPieceName && (
+ <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(pieceConnections)}
+ placeholder={t('Choose connection to replace')}
+ valuesRendering={(value) => (
+ <ConnectionLabel
+ connection={pieceConnections.find(
+ (connection) => connection.id === value,
)}
/>
- <FormMessage />
- </div>
- )}
- />
+ )}
+ />
+ <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,
@@ -185,8 +209,8 @@ function toOptions(connections: AppConnectionWithoutSensitiveData[]) {
}));
}
-function ReplaceConnectionVersionsField() {
- const form = useFormContext<{ applyToPublishedVersions: boolean }>();
+function ReplaceConnectionFlowVersionsField() {
+ const form = useFormContext<ReplaceConnectionFlowVersionsSelection>();
const publishNeedsApproval = flowApprovalsHooks.usePublishNeedsApproval();
return (
<FormField
@@ -228,9 +252,66 @@ function ReplaceConnectionVersionsField() {
);
}
+function ReplaceConnectionTestFlowsAlert({
+ sourceConnection,
+ targetConnections,
+ flowCount,
+}: ReplaceConnectionTestFlowsAlertProps) {
+ const form = useFormContext<ReplaceConnectionSelection>();
+ const targetConnectionId = useWatch({
+ control: form.control,
+ name: 'targetConnectionId',
+ });
+ const targetConnection = targetConnections.find(
+ (connection) => connection.id === targetConnectionId,
+ );
+ if (!targetConnection || !sourceConnection) {
+ return null;
+ }
+ const names: Record<string, string> = {
+ [NEW_NAME_PLACEHOLDER]: targetConnection.displayName,
+ [OLD_NAME_PLACEHOLDER]: sourceConnection.displayName,
+ };
+ const parts = t(
+ "{flowCount, plural, =1 {We recommend testing the flow after the replace. If {newName} can't access the same data as {oldName}, the flow could break.} other {We recommend testing these flows after the replace. If {newName} can't access the same data as {oldName}, they could break.}}",
+ {
+ flowCount,
+ newName: NEW_NAME_PLACEHOLDER,
+ oldName: OLD_NAME_PLACEHOLDER,
+ },
+ ).split(NAME_PLACEHOLDER_PATTERN);
+ return (
+ <Alert>
+ <Info className="size-4" />
+ <AlertDescription>
+ <span>
+ {parts.map((part, index) =>
+ part in names ? (
+ <strong key={index} className="font-semibold">
+ {names[part]}
+ </strong>
+ ) : (
+ part
+ ),
+ )}
+ </span>
+ </AlertDescription>
+ </Alert>
+ );
+}
+
ReplaceConnectionSelectionFields.displayName =
'ReplaceConnectionSelectionFields';
-export { ReplaceConnectionSelectionFields, ReplaceConnectionVersionsField };
+export {
+ ReplaceConnectionSelectionFields,
+ ReplaceConnectionFlowVersionsField,
+ ReplaceConnectionTestFlowsAlert,
+};
+
+const NEW_NAME_PLACEHOLDER = '__AP_NEW_CONNECTION_NAME__';
+const OLD_NAME_PLACEHOLDER = '__AP_OLD_CONNECTION_NAME__';
+const NAME_PLACEHOLDER_PATTERN =
+ /(__AP_NEW_CONNECTION_NAME__|__AP_OLD_CONNECTION_NAME__)/;
export const replaceConnectionSelectionUtils = {
emptySelection: (): ReplaceConnectionSelection => ({
@@ -240,16 +321,46 @@ export const replaceConnectionSelectionUtils = {
}),
};
+export enum ReplaceConnectionSourceKind {
+ CHOOSE = 'CHOOSE',
+ FIXED = 'FIXED',
+}
+
export type ReplaceConnectionSelection = {
pieceName: string;
sourceConnectionId: string;
targetConnectionId: string;
};
+export type ReplaceConnectionFlowVersionsSelection = {
+ applyToPublishedVersions: boolean;
+};
+
+type ReplaceConnectionSource =
+ | {
+ kind: ReplaceConnectionSourceKind.CHOOSE;
+ pieces: PieceMetadataModelSummary[];
+ connections: AppConnectionWithoutSensitiveData[];
+ }
+ | {
+ kind: ReplaceConnectionSourceKind.FIXED;
+ connection: AppConnectionWithoutSensitiveData;
+ };
+
type ReplaceConnectionSelectionFieldsProps = {
- pieces: PieceMetadataModelSummary[];
- sourceConnections: AppConnectionWithoutSensitiveData[];
+ source: ReplaceConnectionSource;
targetConnections: AppConnectionWithoutSensitiveData[];
loading: boolean;
- hideSourceFields?: boolean;
+};
+
+type ReplaceConnectionTestFlowsAlertProps = {
+ sourceConnection: AppConnectionWithoutSensitiveData | undefined;
+ targetConnections: AppConnectionWithoutSensitiveData[];
+ flowCount: number;
+};
+
+type SourceSelectionFieldsProps = {
+ pieces: PieceMetadataModelSummary[];
+ connections: AppConnectionWithoutSensitiveData[];
+ loading: boolean;
};
diff --git a/packages/web/src/app/routes/connections/index.tsx b/packages/web/src/app/routes/connections/index.tsx
index 6f5819242e6..0fd68d9e96a 100644
--- a/packages/web/src/app/routes/connections/index.tsx
+++ b/packages/web/src/app/routes/connections/index.tsx
@@ -40,7 +40,6 @@ import { StatusIconWithText } from '@/components/custom/status-icon-with-text';
import { TextWithTooltip } from '@/components/custom/text-with-tooltip';
import { PlusIcon } from '@/components/icons/plus';
import { ReplaceIcon } from '@/components/icons/replace';
-import { useEmbedding } from '@/components/providers/embed-provider';
import { Button } from '@/components/ui/button';
import {
Tooltip,
@@ -51,6 +50,7 @@ import {
EditGlobalConnectionDialog,
RenameConnectionDialog,
RevalidateConnectionButton,
+ appConnectionsHooks,
appConnectionsMutations,
appConnectionsQueries,
appConnectionUtils,
@@ -70,7 +70,6 @@ function AppConnectionsPage() {
>([]);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const { checkAccess } = useAuthorization();
- const { embedState } = useEmbedding();
const userPlatformRole = userHooks.getCurrentUserPlatformRole();
const location = useLocation();
const { pieces } = piecesHooks.usePieces({});
@@ -128,9 +127,10 @@ function AppConnectionsPage() {
const userHasPermissionToWriteAppConnection = checkAccess(
Permission.WRITE_APP_CONNECTION,
);
- const userHasPermissionToReplaceAppConnection = checkAccess(
- Permission.REPLACE_APP_CONNECTION,
- );
+ const {
+ showReplace,
+ hasPermissionToReplace: userHasPermissionToReplaceAppConnection,
+ } = appConnectionsHooks.useReplaceConnectionAccess();
const { data: owners } = appConnectionsQueries.useConnectionsOwners();
const filters: DataTableFilters<keyof AppConnectionWithoutSensitiveData>[] =
ownerColumnHooks.useOwnerColumnFilter<AppConnectionWithoutSensitiveData>(
@@ -394,7 +394,7 @@ function AppConnectionsPage() {
const toolbarButtons = useMemo(
() => [
- ...(embedState.hideReplaceConnection
+ ...(!showReplace
? []
: [
<PermissionNeededTooltip
@@ -444,7 +444,7 @@ function AppConnectionsPage() {
[
userHasPermissionToWriteAppConnection,
userHasPermissionToReplaceAppConnection,
- embedState.hideReplaceConnection,
+ showReplace,
refresh,
],
);
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 815f9c4c675..3a0cd96d4a1 100644
--- a/packages/web/src/features/connections/hooks/app-connections-hooks.ts
+++ b/packages/web/src/features/connections/hooks/app-connections-hooks.ts
@@ -1,5 +1,6 @@
import {
ApErrorParams,
+ Permission,
ErrorCode,
isNil,
SeekPage,
@@ -36,6 +37,7 @@ 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 { useAuthorization } from '@/hooks/authorization-hooks';
import { api } from '@/lib/api';
import { authenticationSession } from '@/lib/authentication-session';
@@ -79,6 +81,21 @@ type UseUpsertAppConnectionProps = {
) => void;
};
+function useReplaceConnectionAccess() {
+ const { embedState } = useEmbedding();
+ const hasPermissionToReplace = useAuthorization().checkAccess(
+ Permission.REPLACE_APP_CONNECTION,
+ );
+ return {
+ showReplace: !embedState.hideReplaceConnection,
+ hasPermissionToReplace,
+ };
+}
+
+export const appConnectionsHooks = {
+ useReplaceConnectionAccess,
+};
+
export const appConnectionsMutations = {
useUpsertAppConnection: ({
isGlobalConnection,
diff --git a/packages/web/src/features/connections/index.ts b/packages/web/src/features/connections/index.ts
index 1796a0f25b7..e2fb74f144f 100644
--- a/packages/web/src/features/connections/index.ts
+++ b/packages/web/src/features/connections/index.ts
@@ -4,6 +4,7 @@ export { EditGlobalConnectionDialog } from './components/edit-global-connection-
export { RenameConnectionDialog } from './components/rename-connection-dialog';
export { RevalidateConnectionButton } from './components/revalidate-connection-button';
export {
+ appConnectionsHooks,
appConnectionsMutations,
appConnectionsQueries,
} from './hooks/app-connections-hooks';