π OpenHands: AI-Driven Development
fix(automations): show one error toast when an automation action fails (#18043)
Engel Nyst2836ddd7d7ba
diff --git a/__tests__/components/automations/detail/edit-automation-modal.test.tsx b/__tests__/components/automations/detail/edit-automation-modal.test.tsxindex c4188614f9..05b9216c14 100644--- a/__tests__/components/automations/detail/edit-automation-modal.test.tsx+++ b/__tests__/components/automations/detail/edit-automation-modal.test.tsx@@ -459,6 +459,49 @@ describe("EditAutomationModal", () => {expect(onClose).not.toHaveBeenCalled();});+ it("cannot be dismissed while a save is pending, so a failed save still shows its toast", async () => {+ // Arrange β the PATCH stays in flight until the test rejects it.+ let rejectSave: (error: Error) => void = () => {};+ vi.mocked(AutomationService.updateAutomation).mockReturnValue(+ new Promise((_, reject) => {+ rejectSave = reject;+ }),+ );+ const user = userEvent.setup();+ const { container, onClose } = renderModal(dailyAutomation);+ const timeInput = screen.getByTestId("edit-automation-time");+ await user.clear(timeInput);+ await user.type(timeInput, "10:30");+ await user.click(screen.getByTestId("edit-automation-save"));+ await waitFor(() =>+ expect(AutomationService.updateAutomation).toHaveBeenCalledTimes(1),+ );++ // Act β try every dismiss path while the save is pending.+ const backdrop = container.querySelector<HTMLElement>(+ '[role="presentation"]',+ )!;+ // The X in the corner; the footer Cancel button shares its name.+ const [closeButton] = screen.getAllByRole("button", {+ name: "AUTOMATIONS$CANCEL",+ });+ await user.click(backdrop);+ backdrop.focus();+ await user.keyboard("{Escape}");+ await user.click(closeButton);++ // Assert β the dialog stays, and the failure reaches its toast.+ expect(closeButton).toBeDisabled();+ expect(onClose).not.toHaveBeenCalled();+ rejectSave(new Error("backend down"));+ await waitFor(() => {+ expect(displayErrorToast).toHaveBeenCalledTimes(1);+ });+ await waitFor(() => expect(closeButton).toBeEnabled());+ await user.click(closeButton);+ expect(onClose).toHaveBeenCalledTimes(1);+ });+it("persists the newly selected LLM profile in the update payload", async () => {// Arrange β automation currently runs on the "fast" profile, with a// second "careful" profile available to switch to.diff --git a/__tests__/hooks/query/use-automations-backend-switch.test.tsx b/__tests__/hooks/query/use-automations-backend-switch.test.tsxindex 16aed76939..c719380b1e 100644--- a/__tests__/hooks/query/use-automations-backend-switch.test.tsx+++ b/__tests__/hooks/query/use-automations-backend-switch.test.tsx@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import React from "react";import { act, renderHook, waitFor } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { AxiosError, type AxiosResponse } from "axios";import AutomationService from "#/api/automation-service/automation-service.api";import {@@ -15,6 +16,7 @@ import {useCancelAutomationRun,useDispatchAutomation,useDeleteAutomation,+ useImportAutomation,useToggleAutomation,useUpdateAutomation,} from "#/hooks/query/use-automations";@@ -31,6 +33,9 @@ import type {AutomationRunsResponse,} from "#/types/automation";import * as telemetry from "#/services/telemetry";+import { createAgentServerQueryClient } from "#/query-client-config";+import { getApiErrorMessage } from "#/utils/api-error-message";+import * as ToastHandlers from "#/utils/custom-toast-handlers";vi.mock("#/api/automation-service/automation-service.api", () => ({default: {@@ -39,6 +44,7 @@ vi.mock("#/api/automation-service/automation-service.api", () => ({getAutomationRuns: vi.fn(),dispatchAutomation: vi.fn(),cancelAutomationRun: vi.fn(),+ createAutomation: vi.fn(),deleteAutomation: vi.fn(),updateAutomation: vi.fn(),toggleAutomation: vi.fn(),@@ -441,3 +447,169 @@ describe("automation mutation hooks β analytics tracking", () => {);});});++describe("automation mutation hooks β error toasts", () => {+ // The automation service answers a stale id with 404 and a `detail` body.+ const notFound = new AxiosError(+ "Request failed with status code 404",+ "ERR_BAD_REQUEST",+ undefined,+ undefined,+ {+ status: 404,+ data: { detail: "Automation not found" },+ } as AxiosResponse,+ );++ // The app's real client, whose MutationCache toasts unless a mutation opts out.+ function makeAppClientWrapper() {+ const queryClient = createAgentServerQueryClient();+ return function Wrapper({ children }: { children: React.ReactNode }) {+ return (+ <QueryClientProvider client={queryClient}>+ <ActiveBackendProvider>{children}</ActiveBackendProvider>+ </QueryClientProvider>+ );+ };+ }++ // Like the routes and home cards, which render the API message themselves.+ const toastApiMessage = (error: unknown) =>+ ToastHandlers.displayErrorToast(getApiErrorMessage(error, "fallback"));++ let errorToast: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ errorToast = vi+ .spyOn(ToastHandlers, "displayErrorToast")+ .mockImplementation(() => "toast-id");+ vi.mocked(AutomationService.dispatchAutomation).mockRejectedValue(notFound);+ vi.mocked(AutomationService.createAutomation).mockRejectedValue(notFound);+ vi.mocked(AutomationService.updateAutomation).mockRejectedValue(notFound);+ vi.mocked(AutomationService.cancelAutomationRun).mockRejectedValue(+ notFound,+ );+ vi.mocked(AutomationService.toggleAutomation).mockRejectedValue(notFound);+ vi.mocked(AutomationService.deleteAutomation).mockRejectedValue(notFound);+ });++ afterEach(() => {+ errorToast.mockRestore();+ });++ it.each([+ {+ action: "Run now",+ run: () => {+ const { result } = renderHook(() => useDispatchAutomation(), {+ wrapper: makeAppClientWrapper(),+ });+ act(() =>+ result.current.mutate("auto-1", { onError: toastApiMessage }),+ );+ },+ },+ {+ action: "Import",+ run: () => {+ const { result } = renderHook(() => useImportAutomation(), {+ wrapper: makeAppClientWrapper(),+ });+ act(() =>+ result.current.mutate(+ {+ name: "Test",+ prompt: "p",+ trigger: automation.trigger,+ enabled: false,+ },+ { onError: toastApiMessage },+ ),+ );+ },+ },+ {+ action: "Edit save",+ run: () => {+ const { result } = renderHook(() => useUpdateAutomation(), {+ wrapper: makeAppClientWrapper(),+ });+ act(() =>+ result.current.mutate(+ { id: "auto-1", body: { name: "Renamed" } },+ { onError: toastApiMessage },+ ),+ );+ },+ },+ {+ action: "Cancel run",+ run: () => {+ const { result } = renderHook(() => useCancelAutomationRun(), {+ wrapper: makeAppClientWrapper(),+ });+ act(() =>+ result.current.mutate(+ { automationId: "auto-1", runId: "run-1" },+ { onError: toastApiMessage },+ ),+ );+ },+ },+ {+ action: "Toggle opted out with { disableToast: true }",+ run: () => {+ const { result } = renderHook(+ () => useToggleAutomation({ disableToast: true }),+ { wrapper: makeAppClientWrapper() },+ );+ act(() =>+ result.current.mutate(+ { id: "auto-1", enabled: false },+ { onError: toastApiMessage },+ ),+ );+ },+ },+ ])(+ "a failed $action shows only the caller's API-message toast",+ async ({ run }) => {+ // Act+ run();++ // Assert+ // The global MutationCache handler runs before the caller's onError.+ await waitFor(() =>+ expect(errorToast).toHaveBeenCalledWith("Automation not found"),+ );+ expect(errorToast).toHaveBeenCalledTimes(1);+ },+ );++ it.each([+ {+ action: "Toggle",+ run: () => {+ const { result } = renderHook(() => useToggleAutomation(), {+ wrapper: makeAppClientWrapper(),+ });+ act(() => result.current.mutate({ id: "auto-1", enabled: true }));+ },+ },+ {+ action: "Delete",+ run: () => {+ const { result } = renderHook(() => useDeleteAutomation(), {+ wrapper: makeAppClientWrapper(),+ });+ act(() => result.current.mutate("auto-1"));+ },+ },+ ])("a failed $action keeps its one global error toast", async ({ run }) => {+ // Act+ run();++ // Assert+ await waitFor(() => expect(errorToast).toHaveBeenCalledTimes(1));+ });+});diff --git a/__tests__/hooks/use-home-automation-actions.test.tsx b/__tests__/hooks/use-home-automation-actions.test.tsxnew file mode 100644index 0000000000..acaa90b205--- /dev/null+++ b/__tests__/hooks/use-home-automation-actions.test.tsx@@ -0,0 +1,163 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import React from "react";+import { act, renderHook, waitFor } from "@testing-library/react";+import { QueryClientProvider } from "@tanstack/react-query";+import { AxiosError, type AxiosResponse } from "axios";++import AutomationService from "#/api/automation-service/automation-service.api";+import {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import type { Backend } from "#/api/backend-registry/types";+import { ActiveBackendProvider } from "#/contexts/active-backend-context";+import { useHomeAutomationActions } from "#/hooks/use-home-automation-actions";+import { createAgentServerQueryClient } from "#/query-client-config";+import * as telemetry from "#/services/telemetry";+import {+ AutomationRunStatus,+ type Automation,+ type AutomationRun,+} from "#/types/automation";+import * as ToastHandlers from "#/utils/custom-toast-handlers";++vi.mock("#/api/automation-service/automation-service.api", () => ({+ default: {+ dispatchAutomation: vi.fn(),+ cancelAutomationRun: vi.fn(),+ toggleAutomation: vi.fn(),+ },+}));++vi.mock("#/hooks/use-automation-permissions", () => ({+ useAutomationPermissions: () => ({+ canView: true,+ canManage: true,+ isLoading: false,+ }),+ useIsAutomationOwner: () => true,+}));++vi.mock("#/hooks/query/use-settings", () => ({+ useSettings: () => ({ data: { user_consents_to_analytics: false } }),+}));++const localBackend: Backend = {+ id: "local-1",+ name: "Local 1",+ host: "http://localhost:8000",+ apiKey: "session-key",+ kind: "local",+};++const automation: Automation = {+ id: "auto-1",+ name: "Test",+ prompt: "p",+ trigger: { type: "schedule", schedule_human: "Daily" },+ enabled: true,+ repository: "acme/repo",+ model: "daily-profile",+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+};++const runningRun: AutomationRun = {+ id: "run-1",+ status: AutomationRunStatus.RUNNING,+ conversation_id: null,+ bash_command_id: null,+ error_detail: null,+ started_at: "2026-01-02T00:00:00Z",+ completed_at: null,+};++// The automation service answers a stale id with 404 and a `detail` body.+const notFound = new AxiosError(+ "Request failed with status code 404",+ "ERR_BAD_REQUEST",+ undefined,+ undefined,+ {+ status: 404,+ data: { detail: "Automation not found" },+ } as AxiosResponse,+);++// The app's real client, whose MutationCache toasts unless a mutation opts out.+function makeAppClientWrapper() {+ const queryClient = createAgentServerQueryClient();+ return function Wrapper({ children }: { children: React.ReactNode }) {+ return (+ <QueryClientProvider client={queryClient}>+ <ActiveBackendProvider>{children}</ActiveBackendProvider>+ </QueryClientProvider>+ );+ };+}++let errorToast: ReturnType<typeof vi.spyOn>;+let trackEvent: ReturnType<typeof vi.spyOn>;++beforeEach(() => {+ trackEvent = vi.spyOn(telemetry, "trackEvent").mockResolvedValue(undefined);+ errorToast = vi+ .spyOn(ToastHandlers, "displayErrorToast")+ .mockImplementation(() => "toast-id");+ __resetActiveStoreForTests();+ setRegisteredBackends([localBackend]);+ setActiveSelection({ backendId: localBackend.id });+ vi.mocked(AutomationService.dispatchAutomation).mockRejectedValue(notFound);+ vi.mocked(AutomationService.cancelAutomationRun).mockRejectedValue(notFound);+ vi.mocked(AutomationService.toggleAutomation).mockRejectedValue(notFound);+});++afterEach(() => {+ errorToast.mockRestore();+ trackEvent.mockRestore();+ __resetActiveStoreForTests();+});++describe("useHomeAutomationActions β error toasts", () => {+ it.each([+ {+ action: "Run now",+ service: () => AutomationService.dispatchAutomation,+ trigger: (actions: ReturnType<typeof useHomeAutomationActions>) =>+ actions.runNow(),+ },+ {+ action: "Turn off",+ service: () => AutomationService.toggleAutomation,+ trigger: (actions: ReturnType<typeof useHomeAutomationActions>) =>+ actions.confirmTurnOff(),+ },+ {+ action: "Cancel run",+ service: () => AutomationService.cancelAutomationRun,+ trigger: (actions: ReturnType<typeof useHomeAutomationActions>) =>+ actions.cancelRun(),+ },+ ])(+ "a failed home $action shows one toast with the API message",+ async ({ service, trigger }) => {+ // Arrange+ const { result } = renderHook(+ () => useHomeAutomationActions(automation, runningRun),+ { wrapper: makeAppClientWrapper() },+ );++ // Act+ act(() => trigger(result.current));++ // Assert+ await waitFor(() => expect(service()).toHaveBeenCalledTimes(1));+ // The global MutationCache handler runs before the caller's onError.+ await waitFor(() =>+ expect(errorToast).toHaveBeenCalledWith("Automation not found"),+ );+ expect(errorToast).toHaveBeenCalledTimes(1);+ },+ );+});diff --git a/src/components/features/automations/detail/edit-automation-modal.tsx b/src/components/features/automations/detail/edit-automation-modal.tsxindex f35e61af4d..910dbd3338 100644--- a/src/components/features/automations/detail/edit-automation-modal.tsx+++ b/src/components/features/automations/detail/edit-automation-modal.tsx@@ -296,21 +296,28 @@ export function EditAutomationModal({);};+ // Stay open while a save is in flight: the save's error toast is the+ // dialog's own, and it is dropped if the dialog unmounts first.+ const dismiss = () => {+ if (!updateMutation.isPending) onClose();+ };+return (<div className="fixed inset-0 z-50 flex items-center justify-center"><divclassName="absolute inset-0 bg-black/60"- onClick={onClose}+ onClick={dismiss}onKeyDown={(e) => {- if (e.key === "Escape") onClose();+ if (e.key === "Escape") dismiss();}}role="presentation"/><div className="relative w-full max-w-md rounded-xl border border-border bg-surface p-6"><buttontype="button"- onClick={onClose}- className="absolute right-4 top-4 text-muted hover:text-foreground"+ onClick={dismiss}+ disabled={updateMutation.isPending}+ className="absolute right-4 top-4 text-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50"aria-label={t(I18nKey.AUTOMATIONS$CANCEL)}><XMarkIcon className="size-5" />diff --git a/src/hooks/query/use-automations.ts b/src/hooks/query/use-automations.tsindex e57348791a..8274495025 100644--- a/src/hooks/query/use-automations.ts+++ b/src/hooks/query/use-automations.ts@@ -84,13 +84,24 @@ export function useAutomations(options: UseAutomationsOptions = {}) {});}-export function useToggleAutomation() {+interface UseToggleAutomationOptions {+ /**+ * Skip the global error toast, for a caller that shows its own. Dashboard+ * and detail toggles rely on the global toast, so it stays on by default.+ */+ disableToast?: boolean;+}++export function useToggleAutomation({+ disableToast = false,+}: UseToggleAutomationOptions = {}) {const queryClient = useQueryClient();const active = useActiveBackend();const { trackAutomationDisableButton } = useTracking();return useMutation({mutationFn: ({ id, enabled }: { id: string; enabled: boolean }) =>AutomationService.toggleAutomation(id, enabled),+ meta: { disableToast },onSuccess: (_data, variables) => {queryClient.invalidateQueries({ queryKey: AUTOMATIONS_QUERY_KEY });queryClient.invalidateQueries({ queryKey: AUTOMATION_DETAIL_QUERY_KEY });@@ -108,6 +119,8 @@ export function useImportAutomation() {return useMutation({mutationFn: (spec: AutomationSpec) =>AutomationService.createAutomation({ ...spec, enabled: false }),+ // Callers toast the API message themselves; skip the generic global toast.+ meta: { disableToast: true },onSuccess: () => {queryClient.invalidateQueries({ queryKey: AUTOMATIONS_QUERY_KEY });trackAutomationImported({ backendKind: active.backend.kind });@@ -122,6 +135,8 @@ export function useUpdateAutomation() {return useMutation({mutationFn: ({ id, body }: { id: string; body: Partial<Automation> }) =>AutomationService.updateAutomation(id, body),+ // Callers toast the API message themselves; skip the generic global toast.+ meta: { disableToast: true },onSuccess: () => {queryClient.invalidateQueries({ queryKey: AUTOMATIONS_QUERY_KEY });queryClient.invalidateQueries({ queryKey: AUTOMATION_DETAIL_QUERY_KEY });@@ -149,6 +164,8 @@ export function useDispatchAutomation() {const { trackAutomationExecuted } = useTracking();return useMutation({mutationFn: (id: string) => AutomationService.dispatchAutomation(id),+ // Callers toast the API message themselves; skip the generic global toast.+ meta: { disableToast: true },onSuccess: (_run, id) => {queryClient.invalidateQueries({ queryKey: AUTOMATIONS_QUERY_KEY });queryClient.invalidateQueries({ queryKey: AUTOMATION_DETAIL_QUERY_KEY });@@ -169,6 +186,8 @@ export function useCancelAutomationRun() {return useMutation({mutationFn: ({ runId }: { automationId: string; runId: string }) =>AutomationService.cancelAutomationRun(runId),+ // Callers toast the API message themselves; skip the generic global toast.+ meta: { disableToast: true },onSuccess: (_run, { automationId }) => {queryClient.invalidateQueries({ queryKey: AUTOMATIONS_QUERY_KEY });queryClient.invalidateQueries({ queryKey: AUTOMATION_DETAIL_QUERY_KEY });diff --git a/src/hooks/use-home-automation-actions.ts b/src/hooks/use-home-automation-actions.tsindex f83ba1ba31..06e8455dab 100644--- a/src/hooks/use-home-automation-actions.ts+++ b/src/hooks/use-home-automation-actions.ts@@ -50,7 +50,8 @@ export function useHomeAutomationActions(const isDemo = isHomeAutomationsDemoEnabled();const dispatchMutation = useDispatchAutomation();- const toggleMutation = useToggleAutomation();+ // Turn off renders its own error toast with the API message.+ const toggleMutation = useToggleAutomation({ disableToast: true });const cancelMutation = useCancelAutomationRun();const [editOpen, setEditOpen] = useState(false);