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

13.6 KB
Raw Blame
import { isNil, stringifyNullOrUndefined } from '@activepieces/core-utils';
import {
  FlowAction,
  FlowActionType,
  FlowOperationType,
  FlowRun,
  flowOperations,
  flowStructureUtil,
  FlowVersion,
  LoopStepOutput,
  SampleDataFileType,
  StepRunResponse,
  TestStepProgressEvent,
  WebsocketClientEvent,
} from '@activepieces/shared';
import { Socket } from 'socket.io-client';
import { StoreApi } from 'zustand';

import { internalErrorToast } from '@/components/ui/sonner';
import { flowRunUtils } from '@/features/flow-runs';

import { BuilderState } from '../builder-hooks';
import { defaultAgentOutput, isRunAgent } from '../test-step/agent-test-step';

export type UpdateSampleDataParams = {
  stepName: string;
  input?: unknown;
  output?: unknown;
};

export type RunState = {
  run: FlowRun | null;
  setRun: (run: FlowRun, flowVersion: FlowVersion) => void;
  clearRun: (userHasPermissionToEditFlow: boolean) => void;
  loopsIndexes: Record<string, number>;
  setLoopIndex: (stepName: string, index: number) => void;
  selectFailedStep: () => void;
  addActionTestListener: ({
    runId,
    stepName,
  }: {
    runId: string;
    stepName: string;
  }) => void;
  removeStepTestListener: (stepName: string) => void;
  stepTestListeners: Record<string, StepTestListener | null | undefined>;
  updateSampleData: (params: UpdateSampleDataParams) => void;
  errorLogs: Record<string, string | null>;
  setErrorLogs: (stepName: string, error: string | null) => void;
  getErrorLogs: (stepName: string) => string | null;
  setConsoleLogs: (stepName: string, consoleLogs: string | null) => void;
  getConsoleLogs: (stepName: string) => string | null;
  consoleLogs: Record<string, string | null>;
  removeAllStepTestsListeners: () => void;
  isStepBeingTested: (stepName: string) => boolean;
  /**Used to revert the sample data locally when the test is cancelled */
  revertSampleDataLocallyCallbacks: Record<string, (() => void) | undefined>;
  beforeStepTestPreparation: (step: FlowAction) => void;
};
type RunStateInitialState = {
  run: FlowRun | null;
  flowVersion: FlowVersion;
  socket: Socket;
};
type StepTestListener = {
  onProgress: (response: TestStepProgressEvent) => void;
  onFinish: (response: StepRunResponse) => void;
  error: (error: any) => void;
};
export const createRunState = (
  initialState: RunStateInitialState,
  get: StoreApi<BuilderState>['getState'],
  set: StoreApi<BuilderState>['setState'],
): RunState => {
  return {
    revertSampleDataLocallyCallbacks: {},
    run: initialState.run,
    loopsIndexes:
      initialState.run && initialState.run.steps
        ? flowRunUtils.pinLoopsToIterationsWithFailedStep(initialState.run, {})
        : {},
    setRun: async (run: FlowRun, flowVersion: FlowVersion) =>
      set((state) => {
        get().removeAllStepTestsListeners();
        const isNewRun = state.run?.id !== run.id;
        const loopsIndexes = flowRunUtils.pinLoopsToIterationsWithFailedStep(
          run,
          state.loopsIndexes,
          {
            liveFollowPaused:
              !isNewRun && state.userManuallySelectedStepDuringRun,
          },
        );
        return {
          loopsIndexes,
          run,
          flowVersion,
          readonly: true,
          userManuallySelectedStepDuringRun: isNewRun
            ? false
            : state.userManuallySelectedStepDuringRun,
          isStepDataPanelOpen: isNewRun ? true : state.isStepDataPanelOpen,
        };
      }),
    selectFailedStep: () => {
      const { run, selectStepByName } = get();
      if (isNil(run) || isNil(run.failedStep)) {
        return;
      }
      set((state) => ({
        loopsIndexes: flowRunUtils.pinLoopsToIterationsWithFailedStep(
          run,
          state.loopsIndexes,
        ),
      }));
      selectStepByName(run.failedStep.name);
    },
    clearRun: (userHasPermissionToEditFlow: boolean) =>
      set({
        run: null,
        readonly: !userHasPermissionToEditFlow,
        loopsIndexes: {},
        selectedBranchIndex: null,
        userManuallySelectedStepDuringRun: false,
        isStepDataPanelOpen: false,
      }),
    setLoopIndex: (stepName: string, index: number) => {
      set((state) => {
        const parentLoop = flowStructureUtil.getStepOrThrow(
          stepName,
          state.flowVersion.trigger,
        );
        if (parentLoop.type !== FlowActionType.LOOP_ON_ITEMS) {
          console.error(
            `Trying to set loop index for a step that is not a loop: ${stepName}`,
          );
          return state;
        }
        const childLoops = flowStructureUtil
          .getAllChildSteps(parentLoop)
          .filter((c) => c.type === FlowActionType.LOOP_ON_ITEMS)
          .filter((c) => c.name !== stepName);
        const loopsIndexes = { ...state.loopsIndexes };

        loopsIndexes[stepName] = index;

        childLoops.forEach((childLoop) => {
          const childLoopOutput = flowRunUtils.extractStepOutput(
            childLoop.name,
            loopsIndexes,
            state.run?.steps ?? {},
          ) as LoopStepOutput | undefined;

          if (isNil(childLoopOutput) || isNil(childLoopOutput.output)) {
            loopsIndexes[childLoop.name] = 0;
          } else {
            loopsIndexes[childLoop.name] = Math.max(
              Math.min(
                loopsIndexes[childLoop.name],
                childLoopOutput.output.iterations.length - 1,
              ),
              0,
            );
          }
        });
        return {
          loopsIndexes,
          userManuallySelectedStepDuringRun:
            state.userManuallySelectedStepDuringRun || !isNil(state.run),
        };
      });
    },
    addActionTestListener: ({
      runId,
      stepName,
    }: {
      runId: string;
      stepName: string;
    }) => {
      const step = flowStructureUtil.getStep(
        stepName,
        get().flowVersion.trigger,
      );
      if (isNil(step) || !flowStructureUtil.isAction(step?.type)) {
        console.error(`Step ${stepName} not found or is not an action`);
        return;
      }
      const socket = initialState.socket;
      get().beforeStepTestPreparation(step);
      const handleStepFinished = (response: StepRunResponse) => {
        if (response.runId === runId) {
          get().removeStepTestListener(stepName);
          if (response.success) {
            get().updateSampleData({
              stepName: stepName,
              output: response.output,
              input: response.input,
            });
          }
          if (!response.success) {
            get().setErrorLogs(
              stepName,
              response.standardError === '' ? null : response.standardError,
            );
            set((state) => {
              const failedStep = flowStructureUtil.getStep(
                stepName,
                state.flowVersion.trigger,
              );
              return {
                flowVersion: flowOperations.apply(state.flowVersion, {
                  type: FlowOperationType.UPDATE_SAMPLE_DATA_INFO,
                  request: {
                    stepName,
                    sampleDataSettings: failedStep?.settings.sampleData ?? {},
                  },
                }),
              };
            });
          }
          if (step.type === FlowActionType.CODE) {
            get().setConsoleLogs(
              stepName,
              response.standardOutput === '' ? null : response.standardOutput,
            );
          }
        }
      };
      const handleError = (error: any) => {
        get().removeStepTestListener(stepName);
        get().revertSampleDataLocallyCallbacks[stepName]?.();
        console.error(error);
        internalErrorToast();
      };
      socket.on(WebsocketClientEvent.TEST_STEP_FINISHED, handleStepFinished);
      socket.on('error', handleError);
      // Each update carries the whole output, so one that arrives late must not undo a newer one.
      let lastSequence = 0;
      const handleOnProgress = (response: TestStepProgressEvent) => {
        const sequence = response.sequence ?? 0;
        if (
          response.runId !== runId ||
          !response.output ||
          sequence < lastSequence
        ) {
          return;
        }
        lastSequence = sequence;
        get().setSampleDataLocally({
          stepName: stepName,
          type: 'output',
          value: response.output,
        });
      };
      socket.on(WebsocketClientEvent.TEST_STEP_PROGRESS, handleOnProgress);
      set((state) => ({
        stepTestListeners: {
          ...state.stepTestListeners,
          [stepName]: {
            onProgress: handleOnProgress,
            onFinish: handleStepFinished,
            error: handleError,
          },
        },
      }));
    },
    removeStepTestListener: (stepName: string) => {
      set((state) => {
        const socket = initialState.socket;
        const listeners = state.stepTestListeners[stepName];
        if (listeners) {
          socket.off(
            WebsocketClientEvent.TEST_STEP_FINISHED,
            listeners.onFinish,
          );
          socket.off(
            WebsocketClientEvent.TEST_STEP_PROGRESS,
            listeners.onProgress,
          );
          socket.off('error', listeners.error);
        }
        const stepTestListeners = { ...state.stepTestListeners };
        stepTestListeners[stepName] = null;
        return {
          stepTestListeners,
        };
      });
    },
    stepTestListeners: {},
    updateSampleData: ({ stepName, input, output }: UpdateSampleDataParams) => {
      const { setSampleDataLocally, applyOperation, flowVersion } = get();
      const step = flowStructureUtil.getStep(stepName, flowVersion.trigger);
      if (isNil(step)) {
        console.error(`Step ${stepName} not found`);
        internalErrorToast();
        return;
      }

      set((state) => {
        // only update the last test date
        return {
          flowVersion: flowOperations.apply(state.flowVersion, {
            type: FlowOperationType.UPDATE_SAMPLE_DATA_INFO,
            request: {
              stepName: step.name,
              sampleDataSettings: step.settings.sampleData ?? {},
            },
          }),
        };
      });

      setSampleDataLocally({
        stepName: step.name,
        type: 'output',
        value: output,
      });
      const payload = isNil(output) ? stringifyNullOrUndefined(output) : output;
      applyOperation({
        type: FlowOperationType.SAVE_SAMPLE_DATA,
        request: {
          stepName: step.name,
          payload,
          type: SampleDataFileType.OUTPUT,
        },
      });
      if (!isNil(input)) {
        setSampleDataLocally({
          stepName: step.name,
          type: 'input',
          value: input,
        });
        applyOperation({
          type: FlowOperationType.SAVE_SAMPLE_DATA,
          request: {
            stepName: step.name,
            payload: input,
            type: SampleDataFileType.INPUT,
          },
        });
      }
    },
    setErrorLogs: (stepName: string, error: string | null) => {
      set((state) => {
        return {
          errorLogs: {
            ...state.errorLogs,
            [stepName]: error,
          },
        };
      });
    },
    getErrorLogs: (stepName: string) => {
      return get().errorLogs[stepName] ?? null;
    },
    errorLogs: {},
    setConsoleLogs: (stepName: string, consoleLogs: string | null) => {
      set((state) => {
        return {
          consoleLogs: {
            ...state.consoleLogs,
            [stepName]: consoleLogs,
          },
        };
      });
    },
    getConsoleLogs: (stepName: string) => {
      return get().consoleLogs[stepName] ?? null;
    },
    consoleLogs: {},
    removeAllStepTestsListeners: () => {
      const stepTestListeners = get().stepTestListeners;
      Object.keys(stepTestListeners).forEach((stepName) => {
        get().removeStepTestListener(stepName);
      });
    },
    isStepBeingTested: (stepName: string) => {
      return !isNil(get().stepTestListeners[stepName]);
    },
    beforeStepTestPreparation: (step: FlowAction) => {
      const stepName = step.name;
      get().removeStepTestListener(stepName);
      const currentSampleData = get().outputSampleData[stepName];
      const currentErrorLogs = get().errorLogs[stepName];
      const currentConsoleLogs = get().consoleLogs[stepName];
      const currentSampleDataInput = get().inputSampleData[stepName];
      if (isRunAgent(step)) {
        get().setSampleDataLocally({
          stepName: stepName,
          type: 'output',
          value: defaultAgentOutput,
        });
      } else {
        get().setSampleDataLocally({
          stepName: stepName,
          type: 'output',
          value: null,
        });
      }
      get().setErrorLogs(stepName, null);
      get().setConsoleLogs(stepName, null);
      get().setSampleDataLocally({
        stepName: stepName,
        type: 'input',
        value: null,
      });
      const revertSampleDataLocallyCallback = () => {
        get().setSampleDataLocally({
          stepName: stepName,
          type: 'output',
          value: currentSampleData,
        });
        get().setSampleDataLocally({
          stepName: stepName,
          type: 'input',
          value: currentSampleDataInput,
        });
        get().setErrorLogs(stepName, currentErrorLogs);
        get().setConsoleLogs(stepName, currentConsoleLogs);
        set((state) => {
          return {
            revertSampleDataLocallyCallbacks: {
              ...state.revertSampleDataLocallyCallbacks,
              [stepName]: undefined,
            },
          };
        });
      };
      set((state) => {
        return {
          revertSampleDataLocallyCallbacks: {
            ...state.revertSampleDataLocallyCallbacks,
            [stepName]: revertSampleDataLocallyCallback,
          },
        };
      });
    },
  };
};