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(event-streaming): show an error instead of success when saving or deleting a destination fails (#15893)
Bartosz Majewski6f9d172443d6
diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-actions.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-actions.tsxindex 28f7d7f08c4..23a8f139e85 100644--- a/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-actions.tsx+++ b/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-actions.tsx@@ -2,6 +2,7 @@ import { EventDestination } from '@activepieces/shared';import { t } from 'i18next';import { MoreVertical, Pencil, Trash } from 'lucide-react';import { useState } from 'react';+import { toast } from 'sonner';import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';import { Button } from '@/components/ui/button';@@ -11,6 +12,8 @@ import {DropdownMenuContent,DropdownMenuTrigger,} from '@/components/ui/dropdown-menu';+import { INTERNAL_ERROR_MESSAGE } from '@/components/ui/sonner';+import { api } from '@/lib/api';import { eventDestinationsCollectionUtils } from '../lib/event-destinations-collection';@@ -56,9 +59,16 @@ const EventDestinationActions = ({buttonText={t('Delete')}showToastmutationFn={async () => {- if (destination) {- eventDestinationsCollectionUtils.delete([destination.id]);- }+ await eventDestinationsCollectionUtils.delete([destination.id])+ .isPersisted.promise;+ }}+ onError={(error) => {+ toast.error(t('Error'), {+ description: api.extractServerErrorMessage(+ error,+ INTERNAL_ERROR_MESSAGE,+ ),+ });}}isDanger>diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-dialog.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-dialog.tsxindex 9f48408bb42..70edf684bd9 100644--- a/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-dialog.tsx+++ b/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-dialog.tsx@@ -1,4 +1,4 @@-import { isNil } from '@activepieces/core-utils';+import { isNil, tryCatch } from '@activepieces/core-utils';import {ApFlagId,ApplicationEventName,@@ -40,7 +40,9 @@ import {import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';import { ScrollArea } from '@/components/ui/scroll-area';+import { INTERNAL_ERROR_MESSAGE } from '@/components/ui/sonner';import { flagsHooks } from '@/hooks/flags-hooks';+import { api } from '@/lib/api';import { eventDestinationsCollectionUtils } from '../lib/event-destinations-collection';import { handlerFlowBuilder } from '../lib/handler-flow-builder';@@ -123,22 +125,31 @@ const EventDestinationForm = ({},);- const handleSubmit = (data: CreatePlatformEventDestinationRequestBody) => {- if (destination) {- try {- eventDestinationsCollectionUtils.update(destination.id, data);- toast.success(t('Success'), {- description: t('Destination updated successfully'),- });- onClose();- } catch (error) {- toast.error(t('Error'), {- description: error instanceof Error ? error.message : 'Unknown error',- });- }- } else {+ const handleSubmit = async (+ data: CreatePlatformEventDestinationRequestBody,+ ) => {+ if (!destination) {createDestination(data);+ return;}+ const { error } = await tryCatch(+ () =>+ eventDestinationsCollectionUtils.update(destination.id, data)+ .isPersisted.promise,+ );+ if (!isNil(error)) {+ toast.error(t('Error'), {+ description: api.extractServerErrorMessage(+ error,+ INTERNAL_ERROR_MESSAGE,+ ),+ });+ return;+ }+ toast.success(t('Success'), {+ description: t('Destination updated successfully'),+ });+ onClose();};const { mutate: importHandlerFlow, isPending: isImporting } =@@ -205,7 +216,8 @@ const EventDestinationForm = ({};const availableEvents = Object.values(ApplicationEventName);- const isSubmitDisabled = isCreating || isImporting;+ const isSaving = isCreating || form.formState.isSubmitting;+ const isSubmitDisabled = isSaving || isImporting;const isTestingButtonDisabled =isTesting ||@@ -355,7 +367,7 @@ const EventDestinationForm = ({<Buttontype="submit"disabled={isSubmitDisabled}- loading={isCreating}+ loading={isSaving}>{destination ? t('Save changes') : t('Create alert')}</Button>diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-destinations-collection.ts b/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-destinations-collection.tsindex a4d6ab27524..6135e75d157 100644--- a/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-destinations-collection.ts+++ b/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-destinations-collection.ts@@ -109,7 +109,7 @@ export const eventDestinationsCollectionUtils = {destinationId: string,request: UpdatePlatformEventDestinationRequestBody,) => {- eventDestinationsCollection.update(destinationId, (draft) => {+ return eventDestinationsCollection.update(destinationId, (draft) => {Object.assign(draft,Object.fromEntries(@@ -120,7 +120,7 @@ export const eventDestinationsCollectionUtils = {},delete: (destinationIds: string[]) => {- eventDestinationsCollection.delete(destinationIds);+ return eventDestinationsCollection.delete(destinationIds);},useTestEventDestination: () => {diff --git a/packages/web/test/app/routes/platform/infra/event-destinations/components/event-destination-mutations.test.tsx b/packages/web/test/app/routes/platform/infra/event-destinations/components/event-destination-mutations.test.tsxnew file mode 100644index 00000000000..08314b99096--- /dev/null+++ b/packages/web/test/app/routes/platform/infra/event-destinations/components/event-destination-mutations.test.tsx@@ -0,0 +1,296 @@+/**+ * @vitest-environment jsdom+ */+import {+ ApplicationEventName,+ EventDestination,+ EventDestinationScope,+} from '@activepieces/shared';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import * as React from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { toastMock, collectionUtilsMock } = vi.hoisted(() => ({+ toastMock: { success: vi.fn(), error: vi.fn() },+ collectionUtilsMock: {+ update: vi.fn(),+ delete: vi.fn(),+ useCreateEventDestination: () => ({ mutate: vi.fn(), isPending: false }),+ useTestEventDestination: () => ({ mutate: vi.fn(), isPending: false }),+ useImportHandlerFlow: () => ({ mutate: vi.fn(), isPending: false }),+ },+}));++vi.mock('i18next', () => ({ t: (key: string) => key }));++vi.mock('sonner', () => ({ toast: toastMock }));++vi.mock('@/components/ui/sonner', () => ({+ INTERNAL_ERROR_MESSAGE: 'internal error',+}));++vi.mock('@/lib/api', () => ({+ api: {+ extractServerErrorMessage: (error: unknown, fallback: string) =>+ error instanceof Error ? error.message : fallback,+ },+}));++vi.mock('@/hooks/flags-hooks', () => ({+ flagsHooks: { useFlag: () => ({ data: 'http://localhost/api/v1/webhooks' }) },+}));++vi.mock(+ '@/app/routes/platform/infra/event-destinations/lib/event-destinations-collection',+ () => ({ eventDestinationsCollectionUtils: collectionUtilsMock }),+);++vi.mock(+ '@/app/routes/platform/infra/event-destinations/lib/handler-flow-builder',+ () => ({ handlerFlowBuilder: {} }),+);++vi.mock(+ '@/app/routes/platform/infra/event-destinations/lib/use-event-labels',+ () => ({+ useEventLabels: () =>+ new Proxy({}, { get: (_, key) => ({ label: String(key) }) }),+ }),+);++vi.mock('@/components/ui/scroll-area', () => ({+ ScrollArea: ({ children }: React.PropsWithChildren) => <div>{children}</div>,+}));++vi.mock('@/components/ui/checkbox', () => ({+ Checkbox: ({+ checked,+ onCheckedChange,+ id,+ }: {+ checked: boolean;+ onCheckedChange: (checked: boolean) => void;+ id: string;+ }) => (+ <input+ type="checkbox"+ id={id}+ checked={checked}+ onChange={(event) => onCheckedChange(event.target.checked)}+ />+ ),+}));++vi.mock('@/components/ui/dropdown-menu', () => ({+ DropdownMenu: ({ children }: React.PropsWithChildren) => <>{children}</>,+ DropdownMenuTrigger: ({ children }: React.PropsWithChildren) => (+ <>{children}</>+ ),+ DropdownMenuContent: ({ children }: React.PropsWithChildren) => (+ <div>{children}</div>+ ),+ DropdownMenuItem: ({+ children,+ onSelect: _onSelect,+ variant: _variant,+ }: React.PropsWithChildren<{ onSelect?: unknown; variant?: string }>) => (+ <div role="menuitem">{children}</div>+ ),+}));++vi.mock('@/components/ui/dialog', async () => {+ const { createContext, useContext } = await import('react');+ const DialogContext = createContext<{+ open: boolean;+ onOpenChange: (open: boolean) => void;+ }>({ open: false, onOpenChange: () => {} });+ return {+ Dialog: ({+ children,+ open,+ onOpenChange,+ }: React.PropsWithChildren<{+ open: boolean;+ onOpenChange: (open: boolean) => void;+ }>) => (+ <DialogContext.Provider value={{ open, onOpenChange }}>+ {children}+ </DialogContext.Provider>+ ),+ DialogTrigger: ({ children }: React.PropsWithChildren) => {+ const { onOpenChange } = useContext(DialogContext);+ return <span onClick={() => onOpenChange(true)}>{children}</span>;+ },+ DialogContent: ({ children }: React.PropsWithChildren) => {+ const { open } = useContext(DialogContext);+ return open ? <div role="dialog">{children}</div> : null;+ },+ DialogHeader: ({ children }: React.PropsWithChildren) => (+ <div>{children}</div>+ ),+ DialogTitle: ({ children }: React.PropsWithChildren) => (+ <div>{children}</div>+ ),+ DialogDescription: ({ children }: React.PropsWithChildren) => (+ <div>{children}</div>+ ),+ DialogFooter: ({ children }: React.PropsWithChildren) => (+ <div>{children}</div>+ ),+ };+});++vi.mock('@/components/ui/button', () => ({+ Button: ({+ children,+ asChild: _asChild,+ variant: _variant,+ size: _size,+ loading: _loading,+ ...props+ }: React.ComponentProps<'button'> & {+ asChild?: boolean;+ variant?: string;+ size?: string;+ loading?: boolean;+ }) => <button {...props}>{children}</button>,+}));++import EventDestinationActions from '@/app/routes/platform/infra/event-destinations/components/event-destination-actions';+import { EventDestinationDialog } from '@/app/routes/platform/infra/event-destinations/components/event-destination-dialog';++const destination: EventDestination = {+ id: 'dest1',+ created: '2026-01-01T00:00:00.000Z',+ updated: '2026-01-01T00:00:00.000Z',+ platformId: 'platform1',+ scope: EventDestinationScope.PLATFORM,+ events: [ApplicationEventName.FLOW_CREATED],+ url: 'https://old.example.com/hook',+};++const serverError = new Error('Destination not reachable');++function persistedTransaction() {+ return { isPersisted: { promise: Promise.resolve() } };+}++function failedTransaction() {+ return { isPersisted: { promise: Promise.reject(serverError) } };+}++function mount(element: React.ReactElement) {+ render(+ <QueryClientProvider client={new QueryClient()}>+ {element}+ </QueryClientProvider>,+ );+}++function click(element: Element | null | undefined) {+ if (!element) {+ throw new Error('element not found');+ }+ fireEvent.click(element);+}++function findButton(text: string, scope: ParentNode = document.body) {+ return Array.from(scope.querySelectorAll('button')).find(+ (button) => button.textContent === text,+ );+}++function dialogs() {+ return screen.queryAllByRole('dialog');+}++async function settle() {+ await waitFor(() => {+ expect(+ toastMock.error.mock.calls.length + toastMock.success.mock.calls.length,+ ).toBeGreaterThan(0);+ });+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe('EventDestinationDialog edit', () => {+ function openAndSave() {+ mount(+ <EventDestinationDialog destination={destination}>+ <button>open</button>+ </EventDestinationDialog>,+ );+ click(findButton('open'));+ click(findButton('Save changes'));+ }++ it('shows the server error and keeps the dialog open when saving fails', async () => {+ collectionUtilsMock.update.mockImplementation(failedTransaction);++ openAndSave();+ await settle();++ expect(collectionUtilsMock.update).toHaveBeenCalledWith(destination.id, {+ url: destination.url,+ events: destination.events,+ });+ expect(toastMock.error).toHaveBeenCalledWith('Error', {+ description: serverError.message,+ });+ expect(toastMock.success).not.toHaveBeenCalled();+ expect(dialogs()).toHaveLength(1);+ });++ it('shows success and closes the dialog only after saving succeeds', async () => {+ collectionUtilsMock.update.mockImplementation(persistedTransaction);++ openAndSave();+ await settle();++ expect(toastMock.success).toHaveBeenCalledWith('Success', {+ description: 'Destination updated successfully',+ });+ expect(toastMock.error).not.toHaveBeenCalled();+ expect(dialogs()).toHaveLength(0);+ });+});++describe('EventDestinationActions delete', () => {+ function confirmDelete() {+ mount(<EventDestinationActions destination={destination} />);+ const deleteItem = screen+ .getAllByRole('menuitem')+ .find((item) => item.textContent === 'Delete');+ click(deleteItem);+ click(findButton('Delete', dialogs()[0]));+ }++ it('shows the server error instead of success when deleting fails', async () => {+ collectionUtilsMock.delete.mockImplementation(failedTransaction);++ confirmDelete();+ await settle();++ expect(collectionUtilsMock.delete).toHaveBeenCalledWith([destination.id]);+ expect(toastMock.error).toHaveBeenCalledWith('Error', {+ description: serverError.message,+ });+ expect(toastMock.success).not.toHaveBeenCalled();+ expect(dialogs()).toHaveLength(1);+ });++ it('shows success and closes the confirmation only after deleting succeeds', async () => {+ collectionUtilsMock.delete.mockImplementation(persistedTransaction);++ confirmDelete();+ await settle();++ expect(toastMock.success).toHaveBeenCalledWith('Removed {entityName}');+ expect(toastMock.error).not.toHaveBeenCalled();+ expect(dialogs()).toHaveLength(0);+ });+});diff --git a/packages/web/test/app/routes/platform/infra/event-destinations/lib/event-destinations-collection.test.ts b/packages/web/test/app/routes/platform/infra/event-destinations/lib/event-destinations-collection.test.tsnew file mode 100644index 00000000000..233b52e18ed--- /dev/null+++ b/packages/web/test/app/routes/platform/infra/event-destinations/lib/event-destinations-collection.test.ts@@ -0,0 +1,111 @@+// @vitest-environment jsdom+import {+ ApplicationEventName,+ EventDestination,+ EventDestinationScope,+} from '@activepieces/shared';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { apiMock } = vi.hoisted(() => ({+ apiMock: {+ get: vi.fn(),+ post: vi.fn(),+ patch: vi.fn(),+ delete: vi.fn(),+ },+}));++vi.mock('@/lib/api', () => ({ api: apiMock }));+vi.mock('@/features/flows', () => ({+ flowHooks: {},+ flowsApi: {},+ triggerEventsApi: {},+}));+vi.mock('@/features/projects', () => ({ projectCollectionUtils: {} }));+vi.mock('@/hooks/user-hooks', () => ({ userHooks: {} }));++import {+ eventDestinationsCollection,+ eventDestinationsCollectionUtils,+} from '@/app/routes/platform/infra/event-destinations/lib/event-destinations-collection';++const destination: EventDestination = {+ id: 'dest1',+ created: '2026-01-01T00:00:00.000Z',+ updated: '2026-01-01T00:00:00.000Z',+ platformId: 'platform1',+ scope: EventDestinationScope.PLATFORM,+ events: [ApplicationEventName.FLOW_CREATED],+ url: 'https://old.example.com/hook',+};++const serverError = new Error('Request failed with status code 500');++describe('eventDestinationsCollectionUtils', () => {+ beforeEach(async () => {+ vi.clearAllMocks();+ apiMock.get.mockResolvedValue({+ data: [destination],+ next: null,+ previous: null,+ });+ await eventDestinationsCollection.utils.refetch();+ await eventDestinationsCollection.toArrayWhenReady();+ });++ it('update rejects and rolls back when the PATCH fails', async () => {+ apiMock.patch.mockRejectedValue(serverError);++ const transaction = eventDestinationsCollectionUtils.update(+ destination.id,+ { url: 'https://new.example.com/hook', events: destination.events },+ );++ await expect(transaction.isPersisted.promise).rejects.toBe(serverError);+ expect(eventDestinationsCollection.get(destination.id)?.url).toBe(+ destination.url,+ );+ });++ it('update resolves once the PATCH succeeds', async () => {+ apiMock.patch.mockResolvedValue({+ ...destination,+ url: 'https://new.example.com/hook',+ });++ const transaction = eventDestinationsCollectionUtils.update(+ destination.id,+ { url: 'https://new.example.com/hook', events: destination.events },+ );++ await expect(transaction.isPersisted.promise).resolves.toBeDefined();+ expect(apiMock.patch).toHaveBeenCalledWith(+ `/v1/event-destinations/${destination.id}`,+ { url: 'https://new.example.com/hook', events: destination.events },+ );+ });++ it('delete rejects and restores the row when the DELETE fails', async () => {+ apiMock.delete.mockRejectedValue(serverError);++ const transaction = eventDestinationsCollectionUtils.delete([+ destination.id,+ ]);++ await expect(transaction.isPersisted.promise).rejects.toBe(serverError);+ expect(eventDestinationsCollection.has(destination.id)).toBe(true);+ });++ it('delete resolves once the DELETE succeeds', async () => {+ apiMock.delete.mockResolvedValue(undefined);++ const transaction = eventDestinationsCollectionUtils.delete([+ destination.id,+ ]);++ await expect(transaction.isPersisted.promise).resolves.toBeDefined();+ expect(apiMock.delete).toHaveBeenCalledWith(+ `/v1/event-destinations/${destination.id}`,+ );+ });+});