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

19.5 KB
Raw Blame
import { LocalesEnum } from '@activepieces/core-utils';
import {
  PieceMetadataModel,
  PieceMetadataModelSummary,
  PropertyType,
  ExecutePropsResult,
} from '@activepieces/pieces-framework';
import {
  AddPieceRequestBody,
  ApEdition,
  FlowActionType,
  flowPieceUtil,
  PieceAudienceFilter,
  PieceOptionRequest,
  PlatformWithoutSensitiveData,
  FlowTriggerType,
  ApFlagId,
  ApEnvironment,
  SuggestionType,
  TelemetryEventName,
} from '@activepieces/shared';
import {
  QueryClient,
  QueryKey,
  useMutation,
  usePrefetchQuery,
  useQueries,
  useQuery,
  UseQueryResult,
} from '@tanstack/react-query';
import { t } from 'i18next';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import semver from 'semver';

import { useTelemetry } from '@/components/providers/telemetry-provider';
import { appConnectionsApi } from '@/features/connections/api/app-connections';
import {
  StepMetadataWithSuggestions,
  CategorizedStepMetadataWithSuggestions,
} from '@/features/pieces/types';
import { flagsHooks } from '@/hooks/flags-hooks';
import { platformHooks } from '@/hooks/platform-hooks';
import { api } from '@/lib/api';
import { authenticationSession } from '@/lib/authentication-session';

import { piecesApi } from '../api/pieces-api';
import {
  PieceSelectorTabType,
  usePieceSelectorTabs,
} from '../stores/piece-selector-tabs-provider';
import { pieceSearchUtils } from '../utils/piece-search-utils';
import { pieceSelectorCustomization } from '../utils/piece-selector-customization';

import { stepsHooks } from './steps-hooks';

const {
  getPinnedPieces,
  getPopularPieces,
  getAiAndAgentsPieces,
  isUtilityPiece,
  isAppPiece,
  getHighlightedPieces,
  isFlowController,
} = pieceSearchUtils;

type UsePieceModelForStepSettings = {
  name: string;
  version: string | undefined;
  enabled?: boolean;
};

type UsePieceProps = {
  name: string;
  version?: string;
  enabled?: boolean;
  projectId?: string;
  audience?: PieceAudienceFilter;
};

type UsePieceNamesProps = {
  names: string[];
};

type UseMultiplePiecesProps = UsePieceNamesProps & {
  audience?: PieceAudienceFilter;
};

type UsePiecesProps = {
  projectId?: string;
  searchQuery?: string;
  includeHidden?: boolean;
  isTableQuery?: boolean;
  skipProjectFilter?: boolean;
  suggestionType?: SuggestionType;
  enabled?: boolean;
  keepPreviousResults?: boolean;
};
type UsePrefetchPiecesProps = {
  skipProjectFilter?: boolean;
};
type UsePiecesSearchProps = {
  searchQuery: string;
  enabled?: boolean;
  type: 'action' | 'trigger';
  shouldCaptureEvent: boolean;
};

export const pieceQueryKey = ({
  name,
  version,
  locale,
  projectId,
  audience,
}: {
  name: string;
  version: string | undefined;
  locale: string;
  projectId?: string;
  audience?: PieceAudienceFilter;
}): QueryKey => ['piece', name, version, locale, projectId, audience];

export const piecesHooks = {
  usePiece: ({
    name,
    version,
    enabled = true,
    projectId,
    audience,
  }: UsePieceProps) => {
    const { i18n } = useTranslation();
    const query = useQuery<PieceMetadataModel, Error>({
      queryKey: pieceQueryKey({
        name,
        version,
        locale: i18n.language,
        projectId,
        audience,
      }),
      queryFn: () =>
        piecesApi.get({
          name,
          version,
          locale: i18n.language as LocalesEnum,
          projectId,
          audience,
        }),
      staleTime: Infinity,
      enabled,
      retry: (failureCount, error) => {
        if (isPieceNotFoundError(error)) {
          return false;
        }
        return failureCount < 3;
      },
    });
    return {
      pieceModel: query.data,
      isLoading: query.isLoading,
      isSuccess: query.isSuccess,
      isError: query.isError,
      isNotFound: query.isError && isPieceNotFoundError(query.error),
      refetch: query.refetch,
    };
  },
  usePieceModelForStepSettings: ({
    name,
    version,
    enabled = true,
  }: UsePieceModelForStepSettings) => {
    const exactVersion = version
      ? flowPieceUtil.getExactVersion(version)
      : undefined;
    const pieceQuery = piecesHooks.usePiece({
      name,
      version: exactVersion,
      enabled,
      audience: PieceAudienceFilter.ALL,
    });
    return {
      pieceModel: pieceQuery.pieceModel,
      isLoading: pieceQuery.isLoading,
      isSuccess: pieceQuery.isSuccess,
      isNotFound: pieceQuery.isNotFound,
      refetch: pieceQuery.refetch,
    };
  },
  useMultiplePieces: ({ names, audience }: UseMultiplePiecesProps) => {
    const { i18n } = useTranslation();
    return useQueries({
      queries: names.map((name) =>
        latestPieceQueryOptions({ name, language: i18n.language, audience }),
      ),
    });
  },
  usePiecesByName: ({ names, audience }: UseMultiplePiecesProps) => {
    const { i18n } = useTranslation();
    return useQueries({
      queries: names.map((name) =>
        latestPieceQueryOptions({ name, language: i18n.language, audience }),
      ),
      combine: piecesByNameFromResults,
    });
  },
  usePieceSummariesByNames: ({ names }: UsePieceNamesProps) => {
    const { pieces, isLoading } = piecesHooks.usePieces({});
    const summaries = useMemo(() => {
      if (!pieces) return [];
      const byName = new Map(pieces.map((p) => [p.name, p]));
      return names
        .map((name) => byName.get(name))
        .filter((p): p is PieceMetadataModelSummary => !!p);
    }, [pieces, names]);
    return { summaries, isLoading };
  },
  usePieceSummary: ({ name }: { name: string }) => {
    const { pieces, isLoading } = piecesHooks.usePieces({});
    const summary = useMemo(
      () => pieces?.find((p) => p.name === name),
      [pieces, name],
    );
    return { summary, isLoading };
  },
  usePieces: ({
    projectId,
    searchQuery,
    includeHidden = false,
    isTableQuery = false,
    skipProjectFilter = false,
    suggestionType,
    enabled = true,
    keepPreviousResults = false,
  }: UsePiecesProps) => {
    const { i18n } = useTranslation();
    const query = useQuery<PieceMetadataModelSummary[], Error>({
      ...piecesQueryOptions({
        projectId,
        searchQuery,
        includeHidden,
        isTableQuery,
        skipProjectFilter,
        suggestionType,
        locale: i18n.language as LocalesEnum,
        keepPreviousResults,
      }),
      enabled,
    });
    return {
      pieces: query.data,
      isLoading: query.isLoading,
      isError: query.isError,
      error: query.error,
      refetch: query.refetch,
    };
  },
  usePrefetchPieces: ({
    skipProjectFilter = false,
  }: UsePrefetchPiecesProps) => {
    const { i18n } = useTranslation();
    usePrefetchQuery(
      piecesQueryOptions({
        includeHidden: false,
        isTableQuery: false,
        skipProjectFilter,
        locale: i18n.language as LocalesEnum,
      }),
    );
  },
  usePiecesSearch: (
    props: UsePiecesSearchProps,
  ): {
    isLoading: boolean;
    data: CategorizedStepMetadataWithSuggestions[];
  } => {
    const { selectedTab, selectedCustomTabId } = usePieceSelectorTabs();
    const { capture } = useTelemetry();
    const { data: environment } = flagsHooks.useFlag<ApEnvironment>(
      ApFlagId.ENVIRONMENT,
    );
    const { metadata, isLoading: isLoadingPieces } =
      stepsHooks.useAllStepsMetadata(props);
    const { platform } = platformHooks.useCurrentPlatform();
    if (!metadata || isLoadingPieces) {
      return {
        isLoading: true,
        data: [],
      };
    }
    const piecesMetadataWithoutEmptySuggestions =
      filterOutPiecesWithNoSuggestions(metadata);

    const pinnedPieces = getPinnedPieces(
      piecesMetadataWithoutEmptySuggestions,
      platform.pinnedPieces ?? [],
    );

    const popularPieces = getPopularPieces(
      piecesMetadataWithoutEmptySuggestions,
      platform.pinnedPieces ?? [],
    );

    const flowControllerPieces =
      piecesMetadataWithoutEmptySuggestions.filter(isFlowController);

    const utilityPieces =
      piecesMetadataWithoutEmptySuggestions.filter(isUtilityPiece);

    const pieceMetadataWithoutPopularOrPinnedPieces =
      piecesMetadataWithoutEmptySuggestions.filter(
        (p) => !popularPieces.includes(p) && !pinnedPieces.includes(p),
      );

    const appPieces =
      pieceMetadataWithoutPopularOrPinnedPieces.filter(isAppPiece);

    const utilitiesCategory = {
      title: t('Utility'),
      metadata: utilityPieces,
    };
    const flowControllerCategory = {
      title: t('Flow Controller'),
      metadata: flowControllerPieces,
    };
    const appsCategory = {
      title: t('Apps'),
      metadata: appPieces,
    };
    const popularCategory = {
      title: t('Popular'),
      metadata: popularPieces,
    };
    const allCategory = {
      title: t('All'),
      metadata: piecesMetadataWithoutEmptySuggestions,
    };

    switch (selectedTab) {
      case PieceSelectorTabType.EXPLORE:
        return {
          isLoading: false,
          data: getExploreTabContent(
            piecesMetadataWithoutEmptySuggestions,
            platform,
            props.type,
            environment,
          ),
        };
      case PieceSelectorTabType.UTILITY:
        return {
          isLoading: false,
          data: [utilitiesCategory, flowControllerCategory],
        };
      case PieceSelectorTabType.AI_AND_AGENTS:
        return {
          isLoading: false,
          data: getAiAndAgentsPieces(piecesMetadataWithoutEmptySuggestions),
        };
      case PieceSelectorTabType.APPROVALS:
        return {
          isLoading: false,
          data: [],
        };
      case PieceSelectorTabType.CUSTOM: {
        const customTab = pieceSelectorCustomization.getCustomTab({
          config: platform.pieceSelectorConfig,
          customTabId: selectedCustomTabId,
        });
        const categories: CategorizedStepMetadataWithSuggestions[] = [];
        const flatPieces = getPinnedPieces(
          piecesMetadataWithoutEmptySuggestions,
          customTab?.pieceNames ?? [],
        );
        if (flatPieces.length > 0) {
          categories.push({
            title: customTab?.title ?? t('All'),
            metadata: flatPieces,
          });
        }
        for (const section of customTab?.sections ?? []) {
          const sectionPieces = getPinnedPieces(
            piecesMetadataWithoutEmptySuggestions,
            section.pieceNames,
          );
          if (sectionPieces.length > 0) {
            categories.push({
              title: section.title,
              metadata: sectionPieces,
            });
          }
        }
        return {
          isLoading: false,
          data: categories,
        };
      }
      case PieceSelectorTabType.APPS: {
        const popularAppsCategory = {
          ...popularCategory,
          metadata: popularCategory.metadata.filter(isAppPiece),
        };
        const result = {
          isLoading: false,
          data: [popularAppsCategory, appsCategory],
        };
        if (pinnedPieces.length > 0) {
          result.data.unshift({
            title: t('Highlights'),
            metadata: pinnedPieces,
          });
        }
        return result;
      }

      case PieceSelectorTabType.NONE: {
        if (props.shouldCaptureEvent && props.searchQuery.length > 3) {
          capture({
            name: TelemetryEventName.PIECE_SELECTOR_SEARCH,
            payload: {
              search: props.searchQuery,
              isTrigger: props.type === 'trigger',
              selectedActionOrTriggerName: null,
            },
          });
        }
        return {
          isLoading: false,
          data: allCategory.metadata.length > 0 ? [allCategory] : [],
        };
      }
    }
  },
  usePieceOptions: <
    T extends
      | PropertyType.DYNAMIC
      | PropertyType.DROPDOWN
      | PropertyType.MULTI_SELECT_DROPDOWN,
  >({
    onSuccess,
    onError,
    onMutate,
  }: {
    onSuccess: (data: ExecutePropsResult<T>) => void;
    onError: (error: Error) => void;
    onMutate: () => void;
  }) => {
    return useMutation<
      ExecutePropsResult<T>,
      Error,
      { request: PieceOptionRequest; propertyType: T }
    >({
      mutationFn: async ({ request, propertyType }) => {
        onMutate();
        return piecesApi.options(request, propertyType);
      },
      onSuccess,
      onError,
      retry: 1,
      retryDelay: 1000,
    });
  },
  usePieceVersions: (pieceName: string) => {
    const { data: release } = flagsHooks.useFlag<string>(
      ApFlagId.CURRENT_VERSION,
    );
    const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);
    const query = useQuery({
      queryKey: ['pieces-registry', release, edition],
      queryFn: () => piecesApi.registry(release!, edition!),
      staleTime: Infinity,
      enabled: !!pieceName && !!release && !!edition,
      select: (registry) =>
        registry
          .filter((entry) => entry.name === pieceName)
          .map((entry) => ({ version: entry.version }))
          .sort((a, b) => semver.rcompare(a.version, b.version)),
    });
    return {
      pieceVersions: query.data,
      isLoading: query.isLoading,
    };
  },
  usePieceForEmbeddingConnection: ({
    pieceName,
    connectionExternalId,
  }: {
    pieceName: string;
    connectionExternalId: string;
  }) => {
    return useQuery<PieceMetadataModel, Error>({
      queryKey: ['piece', pieceName, connectionExternalId],
      queryFn: async () => {
        const appConnection = (
          await appConnectionsApi.list({
            pieceName,
            limit: 1,
            projectId: authenticationSession.getProjectId()!,
          })
        ).data.find(
          (connection) => connection.externalId === connectionExternalId,
        );
        if (!appConnection) {
          return piecesApi.get({ name: pieceName });
        }
        return piecesApi.get({
          name: appConnection.pieceName,
          version: appConnection.pieceVersion,
        });
      },
      staleTime: Infinity,
    });
  },
};

export const piecesMutations = {
  useInstallPiece: ({
    onSuccess,
    onError,
  }: {
    onSuccess: () => void;
    onError: (error: unknown) => void;
  }) => {
    return useMutation({
      mutationFn: (data: AddPieceRequestBody) => piecesApi.install(data),
      onSuccess,
      onError,
    });
  },
};

const isPieceNotFoundError = (error: unknown) =>
  api.isError(error) && error.response?.status === 404;

const filterOutPiecesWithNoSuggestions = (
  stepsMetadata: StepMetadataWithSuggestions[],
) => {
  return stepsMetadata.filter((metadata) => {
    const isActionWithSuggestions =
      metadata.type === FlowActionType.PIECE &&
      metadata.suggestedActions &&
      metadata.suggestedActions.length > 0;

    const isTriggerWithSuggestions =
      metadata.type === FlowTriggerType.PIECE &&
      metadata.suggestedTriggers &&
      metadata.suggestedTriggers.length > 0;

    const isNotPieceType =
      metadata.type !== FlowActionType.PIECE &&
      metadata.type !== FlowTriggerType.PIECE;
    return (
      isActionWithSuggestions || isTriggerWithSuggestions || isNotPieceType
    );
  });
};

const getExploreTabContent = (
  queryResult: StepMetadataWithSuggestions[],
  platform: PlatformWithoutSensitiveData,
  type: 'action' | 'trigger',
  environment: ApEnvironment | null,
) => {
  const popularCategory: CategorizedStepMetadataWithSuggestions = {
    title: t('Popular'),
    metadata: environment === ApEnvironment.DEVELOPMENT ? queryResult : [],
  };
  if (environment === ApEnvironment.DEVELOPMENT) {
    return [popularCategory];
  }
  const pinnedPieces = getPinnedPieces(
    queryResult,
    platform.pinnedPieces ?? [],
  );
  const popularPieces = getPopularPieces(
    queryResult,
    platform.pinnedPieces ?? [],
  );

  if (popularPieces.length > 0) {
    popularCategory.metadata = [...popularCategory.metadata, ...popularPieces];
  }

  const hightlightedPiecesCategory: CategorizedStepMetadataWithSuggestions = {
    title: t('Highlights'),
    metadata: [],
  };
  const highlightedPieces = getHighlightedPieces(queryResult, type);
  const codePiece = queryResult.find(
    (piece) => piece.type === FlowActionType.CODE,
  );
  const branchPiece = queryResult.find(
    (piece) => piece.type === FlowActionType.ROUTER,
  );
  const loopPiece = queryResult.find(
    (piece) => piece.type === FlowActionType.LOOP_ON_ITEMS,
  );
  const aiRouterPiece = queryResult.find(
    (piece) => piece.type === FlowActionType.AI_ROUTER,
  );

  if (highlightedPieces.length > 0) {
    hightlightedPiecesCategory.metadata.push(...highlightedPieces);
  }

  if (branchPiece) {
    hightlightedPiecesCategory.metadata.splice(0, 0, branchPiece);
  }
  if (aiRouterPiece) {
    hightlightedPiecesCategory.metadata.splice(1, 0, aiRouterPiece);
  }

  if (codePiece) {
    hightlightedPiecesCategory.metadata.splice(3, 0, codePiece);
  }
  if (loopPiece) {
    hightlightedPiecesCategory.metadata.splice(5, 0, loopPiece);
  }
  if (pinnedPieces.length > 0) {
    hightlightedPiecesCategory.metadata = [
      ...pinnedPieces,
      ...hightlightedPiecesCategory.metadata,
    ];
  }

  return [popularCategory, hightlightedPiecesCategory];
};

function latestPieceQueryOptions({
  name,
  language,
  audience,
}: {
  name: string;
  language: string;
  audience?: PieceAudienceFilter;
}) {
  return {
    queryKey: pieceQueryKey({
      name,
      version: undefined,
      locale: language,
      audience,
    }),
    queryFn: () =>
      piecesApi.get({
        name,
        version: undefined,
        locale: Object.values(LocalesEnum).find(
          (locale) => locale === language,
        ),
        audience,
      }),
    staleTime: Infinity,
  };
}

function piecesByNameFromResults(
  results: UseQueryResult<PieceMetadataModel>[],
): Map<string, PieceMetadataModel> {
  return new Map(
    results
      .map((result) => result.data)
      .filter((piece) => piece !== undefined)
      .map((piece) => [piece.name, piece]),
  );
}

function invalidatePieceCaches(queryClient: QueryClient): Promise<void[]> {
  const pieceDerivedQueryKeys = [
    ['pieces'],
    ['pieces-table'],
    ['pieces-metadata'],
    ['piece'],
  ];
  return Promise.all(
    pieceDerivedQueryKeys.map((queryKey) =>
      queryClient.invalidateQueries({ queryKey }),
    ),
  );
}

export const pieceCacheUtils = { invalidatePieceCaches };

function piecesQueryOptions({
  projectId,
  searchQuery,
  includeHidden,
  isTableQuery,
  skipProjectFilter,
  suggestionType,
  locale,
  keepPreviousResults = false,
}: {
  projectId?: string;
  searchQuery?: string;
  includeHidden: boolean;
  isTableQuery: boolean;
  skipProjectFilter: boolean;
  suggestionType?: SuggestionType;
  locale: LocalesEnum;
  keepPreviousResults?: boolean;
}) {
  const queriedProjectId = skipProjectFilter
    ? undefined
    : projectId ?? authenticationSession.getProjectId() ?? undefined;
  return {
    queryKey: [
      isTableQuery ? 'pieces-table' : 'pieces',
      queriedProjectId,
      searchQuery,
      includeHidden,
      skipProjectFilter,
      suggestionType,
      locale,
    ],
    queryFn: () =>
      piecesApi.list({
        projectId: queriedProjectId,
        searchQuery,
        includeHidden,
        suggestionType,
        locale,
      }),
    staleTime: searchQuery ? SEARCH_RESULTS_STALE_TIME_MS : Infinity,
    ...(keepPreviousResults
      ? {
          placeholderData: (
            previousPieces: PieceMetadataModelSummary[] | undefined,
            previousQuery: { queryKey: QueryKey } | undefined,
          ) =>
            previousQuery?.queryKey[PROJECT_ID_KEY_INDEX] === queriedProjectId
              ? previousPieces
              : undefined,
        }
      : {}),
  };
}

const SEARCH_RESULTS_STALE_TIME_MS = 5 * 60 * 1000;
const PROJECT_ID_KEY_INDEX = 1;

export const pieceQueryOptions = { latest: latestPieceQueryOptions };