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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
fix(builder): sending sample data to a webhook trigger no longer spins forever (#16139)
Bartosz Majewski922a4d3bb1c1
diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex b0090f2a804..8f5d2d77954 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -597,6 +597,12 @@"Result #": "Result #","The sample data can be used in the next steps.": "The sample data can be used in the next steps.","There is no sample data available found for this trigger.": "There is no sample data available found for this trigger.",+ "No sample data arrived after {seconds} seconds. It can still arrive while this dialog stays open. If it does not, check the request and the trigger settings, then send again.": "No sample data arrived after {seconds} seconds. It can still arrive while this dialog stays open. If it does not, check the request and the trigger settings, then send again.",+ "This trigger only accepts requests that include its authentication header. Add the header in the Headers tab before you send.": "This trigger only accepts requests that include its authentication header. Add the header in the Headers tab before you send.",+ "This trigger only accepts requests that include the {headerName} header. Add the header in the Headers tab before you send.": "This trigger only accepts requests that include the {headerName} header. Add the header in the Headers tab before you send.",+ "This trigger uses Basic Auth. Add an Authorization header with the username and password from the trigger settings before you send.": "This trigger uses Basic Auth. Add an Authorization header with the username and password from the trigger settings before you send.",+ "This trigger checks an HMAC signature. Add the signature header with the signature of the exact request body before you send. You can also send the sample to the Test URL from the service that signs the request.": "This trigger checks an HMAC signature. Add the signature header with the signature of the exact request body before you send. You can also send the sample to the Test URL from the service that signs the request.",+ "This trigger checks an HMAC signature. Add the {headerName} header with the signature of the exact request body before you send. You can also send the sample to the Test URL from the service that signs the request.": "This trigger checks an HMAC signature. Add the {headerName} header with the signature of the exact request body before you send. You can also send the sample to the Test URL from the service that signs the request.","Failed to run test step, please ensure settings are correct.": "Failed to run test step, please ensure settings are correct.","Internal error, please try again later.": "Internal error, please try again later.","Profile picture updated successfully": "Profile picture updated successfully",diff --git a/packages/web/src/app/builder/test-step/custom-test-step/test-webhook-dialog.tsx b/packages/web/src/app/builder/test-step/custom-test-step/test-webhook-dialog.tsxindex 14cc6f39db9..88881930865 100644--- a/packages/web/src/app/builder/test-step/custom-test-step/test-webhook-dialog.tsx+++ b/packages/web/src/app/builder/test-step/custom-test-step/test-webhook-dialog.tsx@@ -1,14 +1,17 @@+import { isNil } from '@activepieces/core-utils';import { FlowAction, ApFlagId, FlowTrigger } from '@activepieces/shared';import { useMutation } from '@tanstack/react-query';import axios from 'axios';import { t } from 'i18next';-import { useState } from 'react';+import { AlertTriangle, Info } from 'lucide-react';import { ControllerRenderProps, useForm } from 'react-hook-form';+import { toast } from 'sonner';import { z } from 'zod';import { DictionaryInput } from '@/components/custom/dictionary-input';import { JsonEditor } from '@/components/custom/json-editor';import { SearchableSelect } from '@/components/custom/searchable-select';+import { Alert, AlertDescription } from '@/components/ui/alert';import { Button } from '@/components/ui/button';import {Dialog,@@ -22,6 +25,8 @@ import { Form, FormField, FormItem, FormLabel } from '@/components/ui/form';import { Input } from '@/components/ui/input';import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';import { flagsHooks } from '@/hooks/flags-hooks';+import { api } from '@/lib/api';+import { wait } from '@/lib/dom-utils';import { useBuilderStateContext } from '../../builder-hooks';@@ -40,6 +45,8 @@ enum HttpMethod {HEAD = 'HEAD',}+const SAMPLE_DATA_WAIT_SECONDS = 30;+const BodyFormInput = ({bodyType,field,@@ -70,6 +77,20 @@ const WebhookRequest = z.object({method: z.nativeEnum(HttpMethod),});+const CatchWebhookAuthSettings = z.object({+ settings: z.object({+ input: z.object({+ authType: z.enum(['none', 'basic', 'header', 'hmac']),+ authFields: z+ .object({+ headerName: z.string().optional(),+ hmacHeaderName: z.string().optional(),+ })+ .optional(),+ }),+ }),+});+type TestWaitForNextWebhookDialogProps = {currentStep: FlowAction;open: boolean;@@ -88,6 +109,7 @@ type TestWebhookDialogProps =| TestTriggerWebhookDialogProps;const TestTriggerWebhookDialog = ({+ currentStep,open,onOpenChange,}: TestTriggerWebhookDialogProps) => {@@ -95,15 +117,13 @@ const TestTriggerWebhookDialog = ({ApFlagId.WEBHOOK_URL_PREFIX,);const flowId = useBuilderStateContext((state) => state.flow.id);- const [isLoading, setIsLoading] = useState(false);- const { mutate: sendRequest } = useMutation<- unknown,- Error,- z.infer<typeof WebhookRequest>- >({+ const authRequirement = describeAuthRequirement(currentStep);+ const {+ mutate: sendRequest,+ isPending,+ isSuccess: waitExpired,+ } = useMutation<unknown, Error, z.infer<typeof WebhookRequest>>({mutationFn: async (data: z.infer<typeof WebhookRequest>) => {- setIsLoading(true);-await axios({url: `${webhookPrefixUrl}/${flowId}/test`,method: data.method,@@ -111,7 +131,15 @@ const TestTriggerWebhookDialog = ({headers: data.headers,params: data.queryParams,});+ await wait(SAMPLE_DATA_WAIT_SECONDS * 1000);},+ onError: (error) =>+ toast.error(+ api.extractServerErrorMessage(+ error,+ t('Internal error, please try again later.'),+ ),+ ),});return (@@ -125,10 +153,27 @@ const TestTriggerWebhookDialog = ({<DialogHeader><DialogTitle>{t('Send Sample Data to Webhook')}</DialogTitle></DialogHeader>+ {authRequirement && (+ <Alert>+ <Info className="size-4" />+ <AlertDescription>{authRequirement}</AlertDescription>+ </Alert>+ )}+ {waitExpired && (+ <Alert variant="warning">+ <AlertTriangle className="size-4" />+ <AlertDescription>+ {t(+ 'No sample data arrived after {seconds} seconds. It can still arrive while this dialog stays open. If it does not, check the request and the trigger settings, then send again.',+ { seconds: SAMPLE_DATA_WAIT_SECONDS },+ )}+ </AlertDescription>+ </Alert>+ )}<TestWebhookFunctionalityFormshowMethodDropdown={true}onSubmit={sendRequest}- isLoading={isLoading}+ isLoading={isPending}/></DialogContent></Dialog>@@ -364,5 +409,53 @@ const TestWebhookDialog = (props: TestWebhookDialogProps) => {}};+function describeAuthRequirement(trigger: FlowTrigger): string | null {+ const parsed = CatchWebhookAuthSettings.safeParse(trigger);+ if (!parsed.success) {+ return null;+ }+ const { authType, authFields } = parsed.data.settings.input;+ switch (authType) {+ case 'none':+ return null;+ case 'header': {+ const headerName = toLiteralHeaderName(authFields?.headerName);+ if (isNil(headerName)) {+ return t(+ 'This trigger only accepts requests that include its authentication header. Add the header in the Headers tab before you send.',+ );+ }+ return t(+ 'This trigger only accepts requests that include the {headerName} header. Add the header in the Headers tab before you send.',+ { headerName },+ );+ }+ case 'basic':+ return t(+ 'This trigger uses Basic Auth. Add an Authorization header with the username and password from the trigger settings before you send.',+ );+ case 'hmac': {+ const headerName = toLiteralHeaderName(authFields?.hmacHeaderName);+ if (isNil(headerName)) {+ return t(+ 'This trigger checks an HMAC signature. Add the signature header with the signature of the exact request body before you send. You can also send the sample to the Test URL from the service that signs the request.',+ );+ }+ return t(+ 'This trigger checks an HMAC signature. Add the {headerName} header with the signature of the exact request body before you send. You can also send the sample to the Test URL from the service that signs the request.',+ { headerName },+ );+ }+ }+}++function toLiteralHeaderName(headerName: string | undefined): string | null {+ const trimmed = headerName?.trim();+ if (isNil(trimmed) || trimmed === '' || trimmed.includes('{{')) {+ return null;+ }+ return trimmed;+}+TestWebhookDialog.displayName = 'TestWebhookDialog';export default TestWebhookDialog;diff --git a/packages/web/src/app/builder/test-step/utils/test-step-hooks.ts b/packages/web/src/app/builder/test-step/utils/test-step-hooks.tsindex 3a2fb35d3db..0576a593166 100644--- a/packages/web/src/app/builder/test-step/utils/test-step-hooks.ts+++ b/packages/web/src/app/builder/test-step/utils/test-step-hooks.ts@@ -82,7 +82,10 @@ export const testStepHooks = {await wait(2000);attempt++;}- return [];+ if (abortSignal.aborted) {+ return [];+ }+ throw new Error('No sample data received');},onSuccess: async (results) => {if (results.length > 0) {diff --git a/packages/web/test/app/builder/test-step/custom-test-step/test-webhook-dialog.test.tsx b/packages/web/test/app/builder/test-step/custom-test-step/test-webhook-dialog.test.tsxnew file mode 100644index 00000000000..3517e37ef12--- /dev/null+++ b/packages/web/test/app/builder/test-step/custom-test-step/test-webhook-dialog.test.tsx@@ -0,0 +1,240 @@+/**+ * @vitest-environment jsdom+ */+import { FlowTrigger, FlowTriggerType } from '@activepieces/shared';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from '@testing-library/react';+import * as React from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { axiosMock, toastErrorMock, waitMock } = vi.hoisted(() => ({+ axiosMock: vi.fn(),+ toastErrorMock: vi.fn(),+ waitMock: vi.fn(),+}));++vi.mock('i18next', () => ({+ t: (key: string, values?: Record<string, unknown>) =>+ Object.entries(values ?? {}).reduce(+ (text, [name, value]) => text.replace(`{${name}}`, String(value)),+ key,+ ),+}));++vi.mock('axios', () => ({ default: axiosMock }));++vi.mock('@/lib/api', () => ({+ api: {+ extractServerErrorMessage: (error: unknown, fallback: string) =>+ error instanceof Error ? error.message : fallback,+ },+}));++vi.mock('@/lib/dom-utils', () => ({ wait: waitMock }));++vi.mock('sonner', () => ({ toast: { error: toastErrorMock } }));++vi.mock('@/hooks/flags-hooks', () => ({+ flagsHooks: {+ useFlag: () => ({ data: 'https://cloud.example.com/api/v1/webhooks' }),+ },+}));++vi.mock('@/app/builder/builder-hooks', () => ({+ useBuilderStateContext: (+ selector: (state: { flow: { id: string } }) => unknown,+ ) => selector({ flow: { id: 'flow-1' } }),+}));++vi.mock('@/components/custom/json-editor', () => ({+ JsonEditor: () => <div />,+}));++vi.mock('@/components/ui/dialog', () => ({+ Dialog: ({ children, open }: React.PropsWithChildren<{ open: boolean }>) =>+ open ? <div role="dialog">{children}</div> : null,+ DialogClose: ({ children }: React.PropsWithChildren) => <>{children}</>,+ DialogContent: ({ children }: React.PropsWithChildren) => <>{children}</>,+ DialogFooter: ({ children }: React.PropsWithChildren) => <>{children}</>,+ DialogHeader: ({ children }: React.PropsWithChildren) => <>{children}</>,+ DialogTitle: ({ children }: React.PropsWithChildren) => <>{children}</>,+}));++import TestWebhookDialog from '@/app/builder/test-step/custom-test-step/test-webhook-dialog';++const NO_SAMPLE_NOTE =+ 'No sample data arrived after 30 seconds. It can still arrive while this dialog stays open. If it does not, check the request and the trigger settings, then send again.';++function catchWebhookTrigger(input: Record<string, unknown>): FlowTrigger {+ return {+ name: 'trigger',+ valid: true,+ displayName: 'Catch Webhook',+ lastUpdatedDate: '2026-10-07T00:00:00.000Z',+ type: FlowTriggerType.PIECE,+ settings: {+ pieceName: '@activepieces/piece-webhook',+ pieceVersion: '0.1.42',+ triggerName: 'catch_webhook',+ propertySettings: {},+ input,+ },+ };+}++function mount(+ trigger: FlowTrigger = catchWebhookTrigger({ authType: 'none' }),+) {+ const queryClient = new QueryClient({+ defaultOptions: { mutations: { retry: false } },+ });+ return render(+ <QueryClientProvider client={queryClient}>+ <TestWebhookDialog+ testingMode="trigger"+ open={true}+ onOpenChange={vi.fn()}+ currentStep={trigger}+ />+ </QueryClientProvider>,+ );+}++function sendButton() {+ return screen.getByRole<HTMLButtonElement>('button', { name: 'Send' });+}++describe('TestWebhookDialog (trigger)', () => {+ beforeEach(() => {+ axiosMock.mockReset();+ toastErrorMock.mockReset();+ waitMock.mockReset();+ waitMock.mockResolvedValue(undefined);+ });++ it('stops loading and explains when no sample arrives after sending', async () => {+ axiosMock.mockResolvedValue({});+ let finishWait: () => void = () => undefined;+ waitMock.mockImplementation(+ () =>+ new Promise<void>((resolve) => {+ finishWait = resolve;+ }),+ );+ mount();++ fireEvent.click(sendButton());++ await waitFor(() => expect(waitMock).toHaveBeenCalledWith(30000));+ expect(screen.queryAllByRole('button', { name: 'Send' }).length).toBe(0);+ expect(screen.queryAllByText(NO_SAMPLE_NOTE).length).toBe(0);++ act(() => finishWait());++ await screen.findByText(NO_SAMPLE_NOTE);+ expect(axiosMock).toHaveBeenCalledWith(+ expect.objectContaining({+ url: 'https://cloud.example.com/api/v1/webhooks/flow-1/test',+ }),+ );+ expect(sendButton().disabled).toBe(false);+ });++ it('sends a user-typed Authorization header unchanged', async () => {+ axiosMock.mockResolvedValue({});+ mount(catchWebhookTrigger({ authType: 'basic' }));++ fireEvent.mouseDown(screen.getByRole('tab', { name: 'Headers' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Add Item' }));+ const [keyInput, valueInput] = within(+ screen.getByRole('tabpanel'),+ ).getAllByRole('textbox');+ fireEvent.change(keyInput, { target: { value: 'Authorization' } });+ fireEvent.change(valueInput, {+ target: { value: 'Basic dXNlcjpzM2NyZXQ=' },+ });+ fireEvent.click(sendButton());++ await waitFor(() => expect(axiosMock).toHaveBeenCalled());+ expect(axiosMock).toHaveBeenCalledWith(+ expect.objectContaining({+ headers: { Authorization: 'Basic dXNlcjpzM2NyZXQ=' },+ }),+ );+ });++ it('re-enables Send and shows the server error when the request fails', async () => {+ axiosMock.mockRejectedValue(new Error('Payload too large'));+ mount();++ fireEvent.click(sendButton());++ await waitFor(() => expect(axiosMock).toHaveBeenCalled());+ await waitFor(() => expect(sendButton().disabled).toBe(false));+ expect(toastErrorMock).toHaveBeenCalledWith('Payload too large');+ expect(screen.queryAllByText(NO_SAMPLE_NOTE).length).toBe(0);+ });++ it.each([+ {+ name: 'a named auth header',+ input: {+ authType: 'header',+ authFields: { headerName: 'x-api-key', headerValue: 'secret' },+ },+ note: 'This trigger only accepts requests that include the x-api-key header. Add the header in the Headers tab before you send.',+ },+ {+ name: 'an auth header whose name is a template',+ input: {+ authType: 'header',+ authFields: { headerName: "{{connections['webhook-key']}}" },+ },+ note: 'This trigger only accepts requests that include its authentication header. Add the header in the Headers tab before you send.',+ },+ {+ name: 'Basic Auth',+ input: {+ authType: 'basic',+ authFields: { username: 'user', password: 's3cret' },+ },+ note: 'This trigger uses Basic Auth. Add an Authorization header with the username and password from the trigger settings before you send.',+ },+ {+ name: 'an HMAC signature in a named header',+ input: {+ authType: 'hmac',+ authFields: { hmacHeaderName: 'x-signature', hmacSecret: 's3cret' },+ },+ note: 'This trigger checks an HMAC signature. Add the x-signature header with the signature of the exact request body before you send. You can also send the sample to the Test URL from the service that signs the request.',+ },+ {+ name: 'an HMAC signature in a header whose name is a template',+ input: {+ authType: 'hmac',+ authFields: { hmacHeaderName: '{{trigger.signatureHeader}}' },+ },+ note: 'This trigger checks an HMAC signature. Add the signature header with the signature of the exact request body before you send. You can also send the sample to the Test URL from the service that signs the request.',+ },+ ])(+ 'tells the user before sending that the trigger requires $name',+ ({ input, note }) => {+ mount(catchWebhookTrigger(input));++ expect(screen.getByText(note)).toBeTruthy();+ },+ );++ it('shows no auth note when the trigger has no authentication', () => {+ mount(catchWebhookTrigger({ authType: 'none', authFields: {} }));++ expect(screen.queryAllByText(/^This trigger /).length).toBe(0);+ });+});diff --git a/packages/web/test/app/builder/test-step/utils/test-step-hooks.test.tsx b/packages/web/test/app/builder/test-step/utils/test-step-hooks.test.tsxnew file mode 100644index 00000000000..4ac85971ba4--- /dev/null+++ b/packages/web/test/app/builder/test-step/utils/test-step-hooks.test.tsx@@ -0,0 +1,150 @@+/**+ * @vitest-environment jsdom+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act, renderHook, waitFor } from '@testing-library/react';+import * as React from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { listMock, testMock, updateSampleDataMock, waitMock } = vi.hoisted(+ () => ({+ listMock: vi.fn(),+ testMock: vi.fn(),+ updateSampleDataMock: vi.fn(),+ waitMock: vi.fn(),+ }),+);++vi.mock('i18next', () => ({ t: (key: string) => key }));++vi.mock('@/features/flows', () => ({+ triggerEventsApi: { list: listMock, test: testMock },+}));++vi.mock('@/features/flow-runs', () => ({ flowRunsApi: {} }));++vi.mock('@/lib/api', () => ({ api: {} }));++vi.mock('@/components/ui/sonner', () => ({ internalErrorToast: vi.fn() }));++vi.mock('@/lib/authentication-session', () => ({+ authenticationSession: { getProjectId: () => 'project-1' },+}));++vi.mock('@/lib/dom-utils', () => ({ wait: waitMock }));++vi.mock('react-hook-form', () => ({+ useFormContext: () => ({ getValues: () => ({ name: 'trigger' }) }),+}));++vi.mock('@/app/builder/builder-hooks', () => ({+ useBuilderStateContext: (+ selector: (state: {+ flow: { id: string };+ flowVersion: { id: string };+ addActionTestListener: () => void;+ updateSampleData: () => void;+ }) => unknown,+ ) =>+ selector({+ flow: { id: 'flow-1' },+ flowVersion: { id: 'version-1' },+ addActionTestListener: vi.fn(),+ updateSampleData: updateSampleDataMock,+ }),+}));++import { testStepHooks } from '@/app/builder/test-step/utils/test-step-hooks';++function wrapper({ children }: React.PropsWithChildren) {+ const queryClient = new QueryClient({+ defaultOptions: { mutations: { retry: false } },+ });+ return (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+}++function renderSimulateTrigger() {+ const setErrorMessage = vi.fn();+ const onSuccess = vi.fn();+ const { result } = renderHook(+ () => testStepHooks.useSimulateTrigger({ setErrorMessage, onSuccess }),+ { wrapper },+ );+ return { result, setErrorMessage, onSuccess };+}++describe('testStepHooks.useSimulateTrigger', () => {+ beforeEach(() => {+ listMock.mockReset();+ testMock.mockReset();+ updateSampleDataMock.mockReset();+ waitMock.mockReset();+ waitMock.mockResolvedValue(undefined);+ testMock.mockResolvedValue({ data: [] });+ });++ it('reports an error once polling gives up without a new sample', async () => {+ listMock.mockResolvedValue({ data: [{ id: 'old-event', payload: {} }] });+ const { result, setErrorMessage, onSuccess } = renderSimulateTrigger();++ act(() => result.current.mutate(new AbortController().signal));++ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(setErrorMessage).toHaveBeenLastCalledWith(+ 'There is no sample data available found for this trigger.',+ );+ expect(onSuccess).not.toHaveBeenCalled();+ expect(updateSampleDataMock).not.toHaveBeenCalled();+ });++ it('saves the new sample when one arrives', async () => {+ listMock+ .mockResolvedValueOnce({ data: [{ id: 'old-event', payload: {} }] })+ .mockResolvedValue({+ data: [{ id: 'new-event', payload: { hello: 'world' } }],+ });+ const { result, setErrorMessage, onSuccess } = renderSimulateTrigger();++ act(() => result.current.mutate(new AbortController().signal));++ await waitFor(() => expect(onSuccess).toHaveBeenCalled());+ expect(updateSampleDataMock).toHaveBeenCalledWith({+ stepName: 'trigger',+ output: { hello: 'world' },+ });+ expect(setErrorMessage).toHaveBeenLastCalledWith(undefined);+ });++ it('stays silent when the user cancels', async () => {+ listMock.mockResolvedValue({ data: [{ id: 'old-event', payload: {} }] });+ const abortController = new AbortController();+ abortController.abort();+ const { result, setErrorMessage, onSuccess } = renderSimulateTrigger();++ act(() => result.current.mutate(abortController.signal));++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(setErrorMessage).toHaveBeenLastCalledWith(undefined);+ expect(onSuccess).not.toHaveBeenCalled();+ });++ it('stays silent when the user cancels during the last wait', async () => {+ listMock.mockResolvedValue({ data: [{ id: 'old-event', payload: {} }] });+ const abortController = new AbortController();+ waitMock.mockImplementation(async () => {+ if (waitMock.mock.calls.length === 1000) {+ abortController.abort();+ }+ });+ const { result, setErrorMessage, onSuccess } = renderSimulateTrigger();++ act(() => result.current.mutate(abortController.signal));++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(waitMock).toHaveBeenCalledTimes(1000);+ expect(setErrorMessage).toHaveBeenLastCalledWith(undefined);+ expect(onSuccess).not.toHaveBeenCalled();+ });+});