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

7.1 KB
Raw Blame
import { isNil } from '@activepieces/core-utils';
import {
  FlowAction,
  FlowRun,
  FlowRunStatus,
  FlowTrigger,
  flowStructureUtil,
} from '@activepieces/shared';
import { useQuery } from '@tanstack/react-query';
import { t } from 'i18next';
import { ArrowRight } from 'lucide-react';
import { useNavigate } from 'react-router-dom';

import { JsonViewer } from '@/components/custom/json-viewer';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Skeleton } from '@/components/ui/skeleton';
import { flowRunsApi } from '@/features/flow-runs/api/flow-runs-api';
import { flowRunUtils } from '@/features/flow-runs/utils/flow-run-utils';
import { flowHooks } from '@/features/flows/hooks/flow-hooks';
import { stepsHooks } from '@/features/pieces';
import { PieceIcon } from '@/features/pieces/components/piece-icon';
import { authenticationSession } from '@/lib/authentication-session';
import { formatUtils } from '@/lib/format-utils';

type FailedStepDialogProps = {
  run: FlowRun | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
};

export const FailedStepDialog = ({
  run,
  open,
  onOpenChange,
}: FailedStepDialogProps) => {
  const navigate = useNavigate();
  const failedStep = run?.failedStep;
  const isInternalError =
    run?.status === FlowRunStatus.INTERNAL_ERROR && isNil(failedStep);

  const { data: populatedFlow } = flowHooks.useGetFlow({
    flowId: run?.flowId ?? '',
    versionId: run?.flowVersionId,
    enabled: open && !isNil(run) && !isNil(failedStep),
  });

  const { data: populatedRun, isLoading: isLoadingInternalError } = useQuery({
    queryKey: ['flow-run-internal-error', run?.id],
    queryFn: () => flowRunsApi.getPopulated(run!.id),
    enabled: open && !isNil(run) && isInternalError,
  });

  if (isNil(run) || (isNil(failedStep) && !isInternalError)) {
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-lg" />
      </Dialog>
    );
  }

  if (isInternalError) {
    const internalError = populatedRun?.internalError;
    const flowName = run.flowVersion?.displayName ?? '';
    const failureTimestamp = run.finishTime ?? run.startTime ?? run.created;
    const { Icon: RunStatusIcon } = flowRunUtils.getStatusIcon(run.status);
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent
          className="max-w-lg"
          onClick={(e) => e.stopPropagation()}
        >
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-base">
              <RunStatusIcon className="size-4 shrink-0 text-danger-11" />
              <span className="truncate">
                {flowName || t('Internal error')}
              </span>
            </DialogTitle>
            <DialogDescription className="text-xs">
              {failureTimestamp
                ? formatUtils.formatDateWithTime(
                    new Date(failureTimestamp),
                    true,
                  )
                : null}
            </DialogDescription>
          </DialogHeader>
          {isLoadingInternalError ? (
            <Skeleton className="h-40 w-full rounded-md" />
          ) : internalError ? (
            <JsonViewer
              json={internalError.message}
              title={t('Internal error ({source})', {
                source: internalError.source,
              })}
              className="max-h-[400px] overflow-auto"
              hideDownload
            />
          ) : (
            <div className="text-sm italic text-gray-11">
              {t('No error details available')}
            </div>
          )}
          <DialogFooter>
            <Button
              onClick={() =>
                navigate(
                  authenticationSession.appendProjectRoutePrefix(
                    `/runs/${run.id}`,
                  ),
                )
              }
            >
              <ArrowRight className="size-4" />
              {t('Go to run')}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    );
  }

  if (isNil(failedStep)) {
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-lg" />
      </Dialog>
    );
  }

  const flowVersion = populatedFlow?.version;
  const stepNode = flowVersion
    ? flowStructureUtil.getStep(failedStep.name, flowVersion.trigger)
    : undefined;
  const stepNumber = flowVersion
    ? flowStructureUtil.getStepNumber(flowVersion.trigger, failedStep.name)
    : null;
  const flowName =
    run.flowVersion?.displayName ?? flowVersion?.displayName ?? '';
  const failureTimestamp = run.finishTime ?? run.startTime ?? run.created;
  const { Icon: RunStatusIcon } = flowRunUtils.getStatusIcon(run.status);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg" onClick={(e) => e.stopPropagation()}>
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2 text-base">
            <RunStatusIcon className="size-4 shrink-0 text-danger-11" />
            <span className="truncate">{flowName || t('Run Failed')}</span>
          </DialogTitle>
          <DialogDescription className="text-xs">
            {failureTimestamp
              ? formatUtils.formatDateWithTime(new Date(failureTimestamp), true)
              : null}
          </DialogDescription>
        </DialogHeader>
        {failedStep.message ? (
          <JsonViewer
            json={failedStep.message}
            title={
              <span className="flex items-center gap-2 min-w-0">
                {stepNode ? (
                  <StepIconBadge step={stepNode} />
                ) : (
                  <Skeleton className="size-[25px] rounded-md shrink-0" />
                )}
                <span className="truncate">
                  {stepNumber
                    ? `${stepNumber}. ${failedStep.displayName}`
                    : failedStep.displayName}
                </span>
              </span>
            }
            className="max-h-[400px] overflow-auto"
            hideDownload
          />
        ) : (
          <div className="text-sm italic text-gray-11">
            {t('No error message available')}
          </div>
        )}
        <DialogFooter>
          <Button
            onClick={() =>
              navigate(
                authenticationSession.appendProjectRoutePrefix(
                  `/runs/${run.id}`,
                ),
              )
            }
          >
            <ArrowRight className="size-4" />
            {t('Go to run')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

const StepIconBadge = ({ step }: { step: FlowAction | FlowTrigger }) => {
  const { stepMetadata, isLoading } = stepsHooks.useStepMetadata({ step });
  if (isLoading || !stepMetadata) {
    return <Skeleton className="size-[25px] rounded-md shrink-0" />;
  }
  return (
    <PieceIcon
      logoUrl={stepMetadata.logoUrl}
      displayName={stepMetadata.displayName}
      size="xs"
      border={false}
      showTooltip={false}
    />
  );
};