🙌 OpenHands: AI-Driven Development
fix(plugins,apps): show the server's reason once for failed installs and updates (#18025)
Engel Nyst6ae63fde7065
diff --git a/__tests__/hooks/mutation/use-install-canvas-extension.test.ts b/__tests__/hooks/mutation/use-install-canvas-extension.test.tsindex b0f64fbaa3..b60b001092 100644--- a/__tests__/hooks/mutation/use-install-canvas-extension.test.ts+++ b/__tests__/hooks/mutation/use-install-canvas-extension.test.ts@@ -1,5 +1,5 @@import React from "react";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { QueryClientProvider } from "@tanstack/react-query";import { renderHook, waitFor } from "@testing-library/react";import { describe, expect, it, vi, beforeEach } from "vitest";import CanvasExtensionsService from "#/api/canvas-extensions-service";@@ -7,18 +7,25 @@ import {useInstallCanvasExtension,useRefreshCanvasExtension,} from "#/hooks/mutation/use-manage-canvas-extensions";-import { CORS_OR_NETWORK_ERROR_MESSAGE } from "#/utils/user-facing-error";+import i18n from "#/i18n";+import { I18nKey } from "#/i18n/declaration";+import { createAgentServerQueryClient } from "#/query-client-config";-const displayErrorToast = vi.fn();-vi.mock("#/utils/custom-toast-handlers", () => ({- displayErrorToast: (message: string) => displayErrorToast(message),- displaySuccessToast: vi.fn(),+const { toastMock } = vi.hoisted(() => ({+ toastMock: Object.assign(vi.fn(), { success: vi.fn() }),}));+vi.mock("react-hot-toast", () => ({ default: toastMock }));+/** The messages of every error toast shown, in order. */+const errorToastMessages = () =>+ toastMock.mock.calls.map(+ ([content]) =>+ (content as React.ReactElement<{ message: string }>).props.message,+ );++// The app's query client, so its global mutation error toast is in play too.const createWrapper = () => {- const client = new QueryClient({- defaultOptions: { queries: { retry: false }, mutations: { retry: false } },- });+ const client = createAgentServerQueryClient();return function Wrapper({ children }: { children: React.ReactNode }) {return React.createElement(QueryClientProvider, { client }, children);};@@ -45,9 +52,9 @@ describe("useInstallCanvasExtension", () => {vi.clearAllMocks();});- it("surfaces the server's reason instead of the raw HTTP message", async () => {+ it("shows the server's reason once, even when it mentions a failed fetch", async () => {const detail =- "Failed to fetch canvas extension source: Subdirectory 'canvas-puls' not found in local source '/repo'";+ "Could not read canvas extension source: Failed to fetch extension from http://127.0.0.1:9/qa-owner/qa-missing";vi.spyOn(CanvasExtensionsService, "install").mockRejectedValue(new HttpError(400, detail),);@@ -55,13 +62,10 @@ describe("useInstallCanvasExtension", () => {const { result } = renderHook(() => useInstallCanvasExtension(), {wrapper: createWrapper(),});- result.current.mutate({ source: "/repo", repo_path: "canvas-puls" });+ result.current.mutate({ source: "http://127.0.0.1:9/qa-owner/qa-missing" });- await waitFor(() => expect(displayErrorToast).toHaveBeenCalled());- expect(displayErrorToast).toHaveBeenCalledWith(detail);- expect(displayErrorToast).not.toHaveBeenCalledWith(- expect.stringContaining("HTTP request failed"),- );+ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(errorToastMessages()).toEqual([detail]);});it("keeps the shared disconnect wording when the request never lands", async () => {@@ -74,10 +78,29 @@ describe("useInstallCanvasExtension", () => {});result.current.mutate({ source: "/repo" });- await waitFor(() => expect(displayErrorToast).toHaveBeenCalled());- expect(displayErrorToast).toHaveBeenCalledWith(- CORS_OR_NETWORK_ERROR_MESSAGE,+ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(errorToastMessages()).toEqual([+ i18n.t(I18nKey.ERROR$CORS_OR_NETWORK),+ ]);+ });++ it("points to the existing card when the app is already installed", async () => {+ vi.spyOn(CanvasExtensionsService, "install").mockRejectedValue(+ new HttpError(+ 409,+ "Canvas extension already installed. Use force=true to overwrite.",+ ),);++ const { result } = renderHook(() => useInstallCanvasExtension(), {+ wrapper: createWrapper(),+ });+ result.current.mutate({ source: "/repo/demo-page" });++ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(errorToastMessages()).toEqual([+ I18nKey.SETTINGS$APPS_ALREADY_INSTALLED,+ ]);});});@@ -117,11 +140,11 @@ describe("useRefreshCanvasExtension", () => {});});- it("surfaces the server's validation error", async () => {+ it("shows the server's reason when the recorded source is unreachable", async () => {const detail =- "entrypoint 'dist/missing.js' does not resolve to a file in the extension package";+ "Could not read canvas extension source: Failed to fetch extension from github:example/apps";vi.spyOn(CanvasExtensionsService, "install").mockRejectedValue(- new HttpError(422, detail),+ new HttpError(400, detail),);const { result } = renderHook(() => useRefreshCanvasExtension(), {@@ -129,7 +152,7 @@ describe("useRefreshCanvasExtension", () => {});result.current.mutate(installed);- await waitFor(() => expect(displayErrorToast).toHaveBeenCalled());- expect(displayErrorToast).toHaveBeenCalledWith(detail);+ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(errorToastMessages()).toEqual([detail]);});});diff --git a/__tests__/hooks/mutation/use-plugin-mutations.test.ts b/__tests__/hooks/mutation/use-plugin-mutations.test.tsnew file mode 100644index 0000000000..08a9cd84f5--- /dev/null+++ b/__tests__/hooks/mutation/use-plugin-mutations.test.ts@@ -0,0 +1,156 @@+import React from "react";+import { QueryClientProvider } from "@tanstack/react-query";+import { renderHook, waitFor } from "@testing-library/react";+import { HttpError as ClientHttpError } from "@openhands/typescript-client";+import { beforeEach, describe, expect, it, vi } from "vitest";+import PluginsManagementService from "#/api/plugins-management-service";+import { useInstallPlugin } from "#/hooks/mutation/use-install-plugin";+import { useRefreshPlugin } from "#/hooks/mutation/use-refresh-plugin";+import { useSetPluginEnabled } from "#/hooks/mutation/use-set-plugin-enabled";+import { useUninstallPlugin } from "#/hooks/mutation/use-uninstall-plugin";+import i18n from "#/i18n";+import { I18nKey } from "#/i18n/declaration";+import { createAgentServerQueryClient } from "#/query-client-config";++const { toastMock } = vi.hoisted(() => ({+ toastMock: Object.assign(vi.fn(), { success: vi.fn() }),+}));+vi.mock("react-hot-toast", () => ({ default: toastMock }));++/** The messages of every error toast shown, in order. */+const errorToastMessages = () =>+ toastMock.mock.calls.map(+ ([content]) =>+ (content as React.ReactElement<{ message: string }>).props.message,+ );++// The app's query client, so its global mutation error toast is in play too.+const createWrapper = () => {+ const client = createAgentServerQueryClient();+ return function Wrapper({ children }: { children: React.ReactNode }) {+ return React.createElement(QueryClientProvider, { client }, children);+ };+};++/** The shape the shared TypeScript client throws for a failed request. */+class HttpError extends Error {+ status: number;++ response: unknown;++ constructor(status: number, detail: string) {+ super(`HTTP request failed (${status}): ${JSON.stringify({ detail })}`);+ this.name = "HttpError";+ this.status = status;+ this.response = { detail };+ }+}++const SERVER_DETAIL =+ "Failed to fetch plugin source. Check that the source is valid.";++const failingMutations = [+ {+ name: "install",+ method: "installPlugin",+ run: () => {+ const { result } = renderHook(() => useInstallPlugin(), {+ wrapper: createWrapper(),+ });+ result.current.mutate({ source: "qa-not-a-source" });+ return result;+ },+ },+ {+ name: "update",+ method: "refreshPlugin",+ run: () => {+ const { result } = renderHook(() => useRefreshPlugin(), {+ wrapper: createWrapper(),+ });+ result.current.mutate("magic-test");+ return result;+ },+ },+ {+ name: "enable/disable",+ method: "setPluginEnabled",+ run: () => {+ const { result } = renderHook(() => useSetPluginEnabled(), {+ wrapper: createWrapper(),+ });+ result.current.mutate({ name: "magic-test", enabled: false });+ return result;+ },+ },+ {+ name: "uninstall",+ method: "uninstallPlugin",+ run: () => {+ const { result } = renderHook(() => useUninstallPlugin(), {+ wrapper: createWrapper(),+ });+ result.current.mutate("magic-test");+ return result;+ },+ },+] as const;++describe("plugin mutations", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ toastMock.mockClear();+ });++ it.each(failingMutations)(+ "a failed $name shows one toast with the server's reason",+ async ({ method, run }) => {+ vi.spyOn(PluginsManagementService, method).mockRejectedValue(+ new HttpError(400, SERVER_DETAIL),+ );++ const result = run();++ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(errorToastMessages()).toEqual([SERVER_DETAIL]);+ },+ );++ it.each([+ { label: "an empty body", body: "" },+ {+ label: "a plain-text body",+ body: "Bad Gateway: connect ECONNREFUSED 127.0.0.1:18811",+ },+ ])(+ "shows the fallback, not the raw transport text, when the server answers with $label",+ async ({ body }) => {+ vi.spyOn(PluginsManagementService, "installPlugin").mockRejectedValue(+ new ClientHttpError(+ 502,+ "Bad Gateway",+ body,+ `HTTP request failed (502 Bad Gateway): ${JSON.stringify(body)}`,+ ),+ );++ const result = failingMutations[0].run();++ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(errorToastMessages()).toEqual([I18nKey.ERROR$GENERIC]);+ },+ );++ it("keeps the shared disconnect wording when the request never lands", async () => {+ vi.spyOn(PluginsManagementService, "installPlugin").mockRejectedValue(+ new TypeError("Failed to fetch"),+ );++ const result = failingMutations[0].run();++ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(errorToastMessages()).toEqual([+ i18n.t(I18nKey.ERROR$CORS_OR_NETWORK),+ ]);+ });+});diff --git a/__tests__/utils/api-error-message.test.ts b/__tests__/utils/api-error-message.test.tsindex 5cfc4a177a..a51355164d 100644--- a/__tests__/utils/api-error-message.test.ts+++ b/__tests__/utils/api-error-message.test.ts@@ -23,6 +23,65 @@ describe("getApiErrorMessage", () => {);});+ it("returns the reason from an Agent Server unhandled-error body, not its generic `detail`", () => {+ // Arrange — the Agent Server answers unhandled errors with a fixed+ // `detail` and the actual reason under `exception`.+ const error = new HttpError(500, "Internal Server Error", {+ detail: "Internal Server Error",+ exception: "Local extension path does not exist: /plugins/magic-test",+ error_id: "0dd795f8",+ });++ // Act + Assert+ expect(getApiErrorMessage(error, "fallback")).toBe(+ "Local extension path does not exist: /plugins/magic-test",+ );+ });++ it("prefers a specific `detail` over a technical `exception`", () => {+ // Arrange — a friendly `detail` is the server's wording for users.+ const error = new HttpError(500, "Internal Server Error", {+ detail: "Plugin source could not be reached. Check the URL.",+ exception: "ConnectError: [Errno 111] Connection refused",+ });++ // Act + Assert+ expect(getApiErrorMessage(error, "fallback")).toBe(+ "Plugin source could not be reached. Check the URL.",+ );+ });++ it("prefers a validation `detail` array over `exception`", () => {+ const error = new HttpError(422, "Unprocessable Entity", {+ detail: [{ loc: ["body", "source"], msg: "Field required" }],+ exception: "RequestValidationError",+ });++ expect(getApiErrorMessage(error, "fallback")).toBe("Field required");+ });++ it.each([+ { state: "missing", body: {} },+ { state: "empty", body: { detail: "" } },+ ])("returns `exception` when `detail` is $state", ({ body }) => {+ const error = new HttpError(500, "Internal Server Error", {+ ...body,+ exception: "Local extension path does not exist: /plugins/magic-test",+ });++ expect(getApiErrorMessage(error, "fallback")).toBe(+ "Local extension path does not exist: /plugins/magic-test",+ );+ });++ it("returns the generic `detail` when there is no `exception`", () => {+ const error = new HttpError(500, "Internal Server Error", {+ detail: "Internal Server Error",+ });++ expect(getApiErrorMessage(error, "fallback")).toBe("Internal Server Error");+ });+it("returns the `msg` of a single-entry FastAPI validation `detail` array", () => {// Arrange — a provider connection name over 128 characters (#17937).const error = new HttpError(422, "Unprocessable Entity", {diff --git a/src/hooks/mutation/use-install-plugin.ts b/src/hooks/mutation/use-install-plugin.tsindex 5fa2f6f0f5..393a7561fe 100644--- a/src/hooks/mutation/use-install-plugin.ts+++ b/src/hooks/mutation/use-install-plugin.ts@@ -6,10 +6,9 @@ import PluginsManagementService, {import { PLUGINS_QUERY_KEYS } from "#/hooks/query/query-keys";import { I18nKey } from "#/i18n/declaration";import {- displayErrorToast,+ displayApiErrorToast,displaySuccessToast,} from "#/utils/custom-toast-handlers";-import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";/*** Install a plugin from a git source or local path. Installing flips a catalog@@ -21,6 +20,8 @@ export function useInstallPlugin() {const { t } = useTranslation("openhands");return useMutation({+ // This hook toasts the server's reason itself; skip the global toast.+ meta: { disableToast: true },mutationFn: (request: InstallPluginRequest) =>PluginsManagementService.installPlugin(request),onSuccess: () => {@@ -30,10 +31,6 @@ export function useInstallPlugin() {});displaySuccessToast(t(I18nKey.SETTINGS$PLUGINS_INSTALL_SUCCESS));},- onError: (error) => {- displayErrorToast(- retrieveAxiosErrorMessage(error) || t(I18nKey.ERROR$GENERIC),- );- },+ onError: (error) => displayApiErrorToast(error, t(I18nKey.ERROR$GENERIC)),});}diff --git a/src/hooks/mutation/use-manage-canvas-extensions.ts b/src/hooks/mutation/use-manage-canvas-extensions.tsindex b26d0aaae8..26148270fa 100644--- a/src/hooks/mutation/use-manage-canvas-extensions.ts+++ b/src/hooks/mutation/use-manage-canvas-extensions.ts@@ -1,6 +1,7 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import { useTranslation } from "react-i18next";import CanvasExtensionsService from "#/api/canvas-extensions-service";+import { isSdkHttpStatusError } from "#/api/agent-server-compatibility";import type {InstallCanvasExtensionRequest,InstalledCanvasExtensionInfo,@@ -8,10 +9,10 @@ import type {import { CANVAS_EXTENSIONS_QUERY_KEYS } from "#/hooks/query/query-keys";import { I18nKey } from "#/i18n/declaration";import {+ displayApiErrorToast,displayErrorToast,displaySuccessToast,} from "#/utils/custom-toast-handlers";-import { getApiOrConnectionErrorMessage } from "#/utils/api-error-message";function useInvalidateCanvasExtensions() {const queryClient = useQueryClient();@@ -21,12 +22,6 @@ function useInvalidateCanvasExtensions() {});}-// A transport failure carries no response body, so keep the shared-// "Disconnected" wording for it and use the server's detail otherwise.-function displayInstallError(error: unknown, fallback: string) {- displayErrorToast(getApiOrConnectionErrorMessage(error, fallback));-}-export function useInstallCanvasExtension() {const invalidate = useInvalidateCanvasExtensions();const { t } = useTranslation("openhands");@@ -40,7 +35,15 @@ export function useInstallCanvasExtension() {void invalidate();displaySuccessToast(t(I18nKey.SETTINGS$APPS_INSTALL_SUCCESS));},- onError: (error) => displayInstallError(error, t(I18nKey.ERROR$GENERIC)),+ onError: (error) => {+ // The server's 409 says to retry with `force=true`, which the form+ // cannot do; Update or Uninstall on the existing card can.+ if (isSdkHttpStatusError(error, 409)) {+ displayErrorToast(t(I18nKey.SETTINGS$APPS_ALREADY_INSTALLED));+ return;+ }+ displayApiErrorToast(error, t(I18nKey.ERROR$GENERIC));+ },});}@@ -64,7 +67,7 @@ export function useRefreshCanvasExtension() {void invalidate();displaySuccessToast(t(I18nKey.SETTINGS$APPS_REFRESH_SUCCESS));},- onError: (error) => displayInstallError(error, t(I18nKey.ERROR$GENERIC)),+ onError: (error) => displayApiErrorToast(error, t(I18nKey.ERROR$GENERIC)),});}diff --git a/src/hooks/mutation/use-refresh-plugin.ts b/src/hooks/mutation/use-refresh-plugin.tsindex a5d330d974..f6b28eb320 100644--- a/src/hooks/mutation/use-refresh-plugin.ts+++ b/src/hooks/mutation/use-refresh-plugin.ts@@ -4,10 +4,9 @@ import PluginsManagementService from "#/api/plugins-management-service";import { PLUGINS_QUERY_KEYS } from "#/hooks/query/query-keys";import { I18nKey } from "#/i18n/declaration";import {- displayErrorToast,+ displayApiErrorToast,displaySuccessToast,} from "#/utils/custom-toast-handlers";-import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";/*** Update an installed plugin from its source. Version / resolved coordinates may@@ -18,15 +17,13 @@ export function useRefreshPlugin() {const { t } = useTranslation("openhands");return useMutation({+ // This hook toasts the server's reason itself; skip the global toast.+ meta: { disableToast: true },mutationFn: (name: string) => PluginsManagementService.refreshPlugin(name),onSuccess: () => {queryClient.invalidateQueries({ queryKey: PLUGINS_QUERY_KEYS.installed });displaySuccessToast(t(I18nKey.SETTINGS$PLUGINS_REFRESH_SUCCESS));},- onError: (error) => {- displayErrorToast(- retrieveAxiosErrorMessage(error) || t(I18nKey.ERROR$GENERIC),- );- },+ onError: (error) => displayApiErrorToast(error, t(I18nKey.ERROR$GENERIC)),});}diff --git a/src/hooks/mutation/use-set-plugin-enabled.ts b/src/hooks/mutation/use-set-plugin-enabled.tsindex ef5b417fdf..c8fb03649f 100644--- a/src/hooks/mutation/use-set-plugin-enabled.ts+++ b/src/hooks/mutation/use-set-plugin-enabled.ts@@ -3,8 +3,7 @@ import { useTranslation } from "react-i18next";import PluginsManagementService from "#/api/plugins-management-service";import { PLUGINS_QUERY_KEYS } from "#/hooks/query/query-keys";import { I18nKey } from "#/i18n/declaration";-import { displayErrorToast } from "#/utils/custom-toast-handlers";-import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";+import { displayApiErrorToast } from "#/utils/custom-toast-handlers";/*** Enable or disable an installed plugin. Enabled installed plugins auto-load@@ -16,15 +15,13 @@ export function useSetPluginEnabled() {const { t } = useTranslation("openhands");return useMutation({+ // This hook toasts the server's reason itself; skip the global toast.+ meta: { disableToast: true },mutationFn: ({ name, enabled }: { name: string; enabled: boolean }) =>PluginsManagementService.setPluginEnabled(name, enabled),onSuccess: () => {queryClient.invalidateQueries({ queryKey: PLUGINS_QUERY_KEYS.installed });},- onError: (error) => {- displayErrorToast(- retrieveAxiosErrorMessage(error) || t(I18nKey.ERROR$GENERIC),- );- },+ onError: (error) => displayApiErrorToast(error, t(I18nKey.ERROR$GENERIC)),});}diff --git a/src/hooks/mutation/use-uninstall-plugin.ts b/src/hooks/mutation/use-uninstall-plugin.tsindex 3dbf63051b..6bd36ce3c4 100644--- a/src/hooks/mutation/use-uninstall-plugin.ts+++ b/src/hooks/mutation/use-uninstall-plugin.ts@@ -4,10 +4,9 @@ import PluginsManagementService from "#/api/plugins-management-service";import { PLUGINS_QUERY_KEYS } from "#/hooks/query/query-keys";import { I18nKey } from "#/i18n/declaration";import {- displayErrorToast,+ displayApiErrorToast,displaySuccessToast,} from "#/utils/custom-toast-handlers";-import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";/*** Uninstall a plugin. The plugin returns to "available" in the catalog, so both@@ -18,6 +17,8 @@ export function useUninstallPlugin() {const { t } = useTranslation("openhands");return useMutation({+ // This hook toasts the server's reason itself; skip the global toast.+ meta: { disableToast: true },mutationFn: (name: string) =>PluginsManagementService.uninstallPlugin(name),onSuccess: () => {@@ -27,10 +28,6 @@ export function useUninstallPlugin() {});displaySuccessToast(t(I18nKey.SETTINGS$PLUGINS_UNINSTALL_SUCCESS));},- onError: (error) => {- displayErrorToast(- retrieveAxiosErrorMessage(error) || t(I18nKey.ERROR$GENERIC),- );- },+ onError: (error) => displayApiErrorToast(error, t(I18nKey.ERROR$GENERIC)),});}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 44ad11ca0c..31d173914c 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -35512,6 +35512,23 @@"uk": "Застосунок встановлено. Перевірте його тут і ввімкніть, коли будете готові.","ca": "Aplicació instal·lada. Revisa-la aquí i activa-la quan estiguis a punt."},+ "SETTINGS$APPS_ALREADY_INSTALLED": {+ "en": "This app is already installed. Use Update or Uninstall on its card.",+ "ja": "このアプリはすでにインストールされています。カードの「更新」または「アンインストール」を使用してください。",+ "zh-CN": "此应用已安装。请使用其卡片上的“更新”或“卸载”。",+ "zh-TW": "此應用程式已安裝。請使用其卡片上的「更新」或「解除安裝」。",+ "ko-KR": "이 앱은 이미 설치되어 있습니다. 카드의 업데이트 또는 제거를 사용하세요.",+ "no": "Denne appen er allerede installert. Bruk Oppdater eller Avinstaller på kortet.",+ "ar": "هذا التطبيق مثبت بالفعل. استخدم تحديث أو إزالة التثبيت على بطاقته.",+ "de": "Diese App ist bereits installiert. Verwende Aktualisieren oder Deinstallieren auf ihrer Karte.",+ "fr": "Cette application est déjà installée. Utilisez Mettre à jour ou Désinstaller sur sa carte.",+ "it": "Questa app è già installata. Usa Aggiorna o Disinstalla sulla sua scheda.",+ "pt": "Este aplicativo já está instalado. Use Atualizar ou Desinstalar no cartão dele.",+ "es": "Esta aplicación ya está instalada. Usa Actualizar o Desinstalar en su tarjeta.",+ "tr": "Bu uygulama zaten yüklü. Kartındaki Güncelle veya Kaldır seçeneğini kullanın.",+ "uk": "Цей застосунок уже встановлено. Скористайтеся кнопкою Оновити або Видалити на його картці.",+ "ca": "Aquesta aplicació ja està instal·lada. Fes servir Actualitza o Desinstal·la a la seva targeta."+ },"SETTINGS$APPS_REFRESH_SUCCESS": {"en": "App updated.","ja": "アプリを更新しました。",diff --git a/src/utils/api-error-message.ts b/src/utils/api-error-message.tsindex ba0eac2e38..615c866b35 100644--- a/src/utils/api-error-message.ts+++ b/src/utils/api-error-message.ts@@ -49,11 +49,21 @@ function getValidationDetailMessage(detail: unknown): string | null {.join("; ");}+/**+ * The fixed `detail` the Agent Server sends with every 5xx (an unhandled+ * error, or an `HTTPException` with a 5xx status); the reason is under+ * `exception` instead.+ */+const AGENT_SERVER_GENERIC_DETAIL = "Internal Server Error";+/*** Extract a human-readable message from a failed API call. Prefers the- * server-provided `message`/`detail`/`error` fields (including a FastAPI- * validation `detail` array), then the `Error` message, then `fallback`.- * The shared client's `HttpError` message is the raw transport text+ * server-provided `message`/`detail`/`exception`/`error` fields (including a+ * FastAPI validation `detail` array), then the `Error` message, then+ * `fallback`. `exception` is used only when `detail` is missing, empty or the+ * Agent Server's generic "Internal Server Error", so a specific `detail`+ * always wins over the technical `exception` text. The shared client's+ * `HttpError` message is the raw transport text* (`HTTP request failed (status): {json}`), so it is never shown: an* `HttpError` without a usable body yields `fallback`.*/@@ -63,17 +73,28 @@ export function getApiErrorMessage(error: unknown, fallback: string): string {if (body && typeof body === "object") {const {message,+ exception,detail,error: bodyError,} = body as {message?: unknown;+ exception?: unknown;detail?: unknown;error?: unknown;};if (typeof message === "string" && message) return message;- if (typeof detail === "string" && detail) return detail;- const validationMessage = getValidationDetailMessage(detail);- if (validationMessage) return validationMessage;+ const detailMessage =+ typeof detail === "string" && detail+ ? detail+ : getValidationDetailMessage(detail);+ if (+ typeof exception === "string" &&+ exception &&+ (!detailMessage || detailMessage === AGENT_SERVER_GENERIC_DETAIL)+ ) {+ return exception;+ }+ if (detailMessage) return detailMessage;if (typeof bodyError === "string" && bodyError) return bodyError;}@@ -82,6 +103,15 @@ export function getApiErrorMessage(error: unknown, fallback: string): string {return fallback;}+/**+ * Whether the server answered a failed call: there is a response body, or the+ * shared client's `HttpError` (a non-2xx status, possibly with an empty body).+ * A network failure or timeout has neither.+ */+export function hasApiErrorResponse(error: unknown): boolean {+ return Boolean(getApiErrorBody(error)) || isSdkHttpError(error);+}+/*** Like {@link getApiErrorMessage}, but a request that never got an answer* (a network failure or timeout: no response body and no `HttpError`) keeps@@ -92,7 +122,7 @@ export function getApiOrConnectionErrorMessage(error: unknown,fallback: string,): string {- if (getApiErrorBody(error) || isSdkHttpError(error)) {+ if (hasApiErrorResponse(error)) {return getApiErrorMessage(error, fallback);}return retrieveAxiosErrorMessage(error) || fallback;diff --git a/src/utils/custom-toast-handlers.tsx b/src/utils/custom-toast-handlers.tsxindex bea1fe3c86..62342d60d0 100644--- a/src/utils/custom-toast-handlers.tsx+++ b/src/utils/custom-toast-handlers.tsx@@ -11,6 +11,10 @@ import {isCorsOrNetworkErrorMessage,} from "./user-facing-error";import { buildAgentCanvasPath } from "#/utils/base-path";+import {+ getApiOrConnectionErrorMessage,+ hasApiErrorResponse,+} from "./api-error-message";// react-hot-toast accepts only CSSProperties via the style option — cannot use classNameconst TOAST_STYLE: CSSProperties = {@@ -94,6 +98,14 @@ export const ERROR_TOAST_OPTIONS: ToastOptions = {style: ERROR_TOAST_STYLE,};+function showErrorToast(message: string) {+ const duration = calculateToastDuration(message, 4000);+ toast(<ErrorToastContent message={message} />, {+ ...ERROR_TOAST_OPTIONS,+ duration,+ });+}+export const displayErrorToast = (error: string | null | undefined) => {let errorMessage = error || i18n.t(I18nKey.STATUS$ERROR);if (isCorsOrNetworkErrorMessage(errorMessage)) {@@ -101,11 +113,22 @@ export const displayErrorToast = (error: string | null | undefined) => {} else if (isBackendRequestTimeoutMessage(errorMessage)) {errorMessage = i18n.t(I18nKey.ERROR$BACKEND_REQUEST_TIMEOUT);}- const duration = calculateToastDuration(errorMessage, 4000);- toast(<ErrorToastContent message={errorMessage} />, {- ...ERROR_TOAST_OPTIONS,- duration,- });+ showErrorToast(errorMessage);+};++/**+ * Toast a failed API call. When the server answered, its own reason (see+ * `getApiErrorMessage`) is shown as sent, even if it happens to mention+ * "Failed to fetch"; only a failure with no response (network, CORS, timeout)+ * gets the shared "Disconnected" wording.+ */+export const displayApiErrorToast = (error: unknown, fallback: string) => {+ const message = getApiOrConnectionErrorMessage(error, fallback);+ if (hasApiErrorResponse(error)) {+ showErrorToast(message);+ } else {+ displayErrorToast(message);+ }};export const displaySuccessToast = (message: string) => {