Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(settings): show the server's message instead of raw HttpError text in profile error toasts (#18030)

Engel Nyst3450c2c2ac1b
diff --git a/__tests__/components/settings/llm-profiles/rename-profile-modal.test.tsx b/__tests__/components/settings/llm-profiles/rename-profile-modal.test.tsx
index 5985b91876..26b484d654 100644
--- a/__tests__/components/settings/llm-profiles/rename-profile-modal.test.tsx
+++ b/__tests__/components/settings/llm-profiles/rename-profile-modal.test.tsx
@@ -3,6 +3,7 @@ import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import userEvent from "@testing-library/user-event";
import React from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { HttpError } from "@openhands/typescript-client";
import { RenameProfileModal } from "#/components/features/settings/llm-profiles/rename-profile-modal";
import { ProfileInfo } from "#/api/profiles-service/profiles-service.api";
import ProfilesService from "#/api/profiles-service/profiles-service.api";
@@ -233,6 +234,39 @@ describe("RenameProfileModal", () => {
expect(screen.getByTestId("rename-profile-modal")).toBeInTheDocument();
});
+ it("shows the server's `detail` instead of the raw HttpError text when the new name already exists (#17937)", async () => {
+ // Arrange β€” the agent-server refuses a duplicate name with a FastAPI 409,
+ // which the shared TypeScript client throws as an HttpError.
+ const user = userEvent.setup();
+ const { displayErrorToast } = await import(
+ "#/utils/custom-toast-handlers"
+ );
+ vi.mocked(ProfilesService.renameProfile).mockRejectedValue(
+ new HttpError(
+ 409,
+ "Conflict",
+ { detail: "Profile 'taken-name' already exists" },
+ `HTTP request failed (409 Conflict): {"detail":"Profile 'taken-name' already exists"}`,
+ ),
+ );
+ const onClose = vi.fn();
+ renderModal(mockProfile, onClose);
+
+ // Act
+ const input = screen.getByTestId("rename-profile-input");
+ await user.clear(input);
+ await user.type(input, "taken-name");
+ await user.click(screen.getByTestId("rename-profile-submit"));
+
+ // Assert
+ await waitFor(() => {
+ expect(displayErrorToast).toHaveBeenCalledWith(
+ "Profile 'taken-name' already exists",
+ );
+ });
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
it("submits form when Enter key is pressed with valid name", async () => {
const user = userEvent.setup();
const handleClose = vi.fn();
diff --git a/__tests__/hooks/mutation/use-switch-llm-profile.test.tsx b/__tests__/hooks/mutation/use-switch-llm-profile.test.tsx
index d4a3c8f9da..33b552bf18 100644
--- a/__tests__/hooks/mutation/use-switch-llm-profile.test.tsx
+++ b/__tests__/hooks/mutation/use-switch-llm-profile.test.tsx
@@ -1,6 +1,7 @@
import { renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { AxiosError, AxiosHeaders } from "axios";
+import { HttpError } from "@openhands/typescript-client";
import { describe, expect, it, vi, beforeEach } from "vitest";
import { useSwitchLlmProfile } from "#/hooks/mutation/use-switch-llm-profile";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
@@ -15,6 +16,10 @@ import {
setStoredConversationMetadata,
} from "#/api/conversation-metadata-store";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
+import {
+ BACKEND_REQUEST_TIMEOUT_MESSAGE,
+ CORS_OR_NETWORK_ERROR_MESSAGE,
+} from "#/utils/user-facing-error";
vi.mock("#/utils/custom-toast-handlers");
@@ -148,7 +153,7 @@ describe("useSwitchLlmProfile", () => {
// failed switch keeps the specific "Switched to {name} failed" message
// (#1571 review).
it("shows the tailored switch-failed message when the error carries no server detail", async () => {
- // An empty-message Error extracts to "" (see retrieveAxiosErrorMessage),
+ // An empty-message Error carries no usable message (see getApiErrorMessage),
// so the tailored fallback is what actually renders.
vi.mocked(AgentServerConversationService.switchProfile).mockRejectedValue(
new Error(),
@@ -189,6 +194,80 @@ describe("useSwitchLlmProfile", () => {
);
});
+ it("shows the server's `detail` instead of the raw HttpError text for an unknown profile (#17937)", async () => {
+ // Arrange β€” the agent-server answers /switch_profile with a FastAPI 404,
+ // which the shared TypeScript client throws as an HttpError.
+ vi.mocked(AgentServerConversationService.switchProfile).mockRejectedValue(
+ new HttpError(
+ 404,
+ "Not Found",
+ { detail: "Profile 'qa-nope' not found" },
+ `HTTP request failed (404 Not Found): {"detail":"Profile 'qa-nope' not found"}`,
+ ),
+ );
+
+ // Act
+ const { result } = renderSwitchHook();
+ result.current.mutate({ conversationId: "conv-1", profileName: "qa-nope" });
+
+ // Assert
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(displayErrorToast).toHaveBeenCalledWith(
+ "Profile 'qa-nope' not found",
+ );
+ });
+
+ it("falls back to the tailored switch-failed message for an HttpError without a server detail", async () => {
+ vi.mocked(AgentServerConversationService.switchProfile).mockRejectedValue(
+ new HttpError(
+ 502,
+ "Bad Gateway",
+ null,
+ "HTTP request failed (502 Bad Gateway): null",
+ ),
+ );
+
+ const { result } = renderSwitchHook();
+ result.current.mutate({ conversationId: "conv-1", profileName: "Smart" });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(displayErrorToast).toHaveBeenCalledWith("MODEL$SWITCH_FAILED");
+ });
+
+ it("keeps the shared disconnect wording when the switch request never reaches the server", async () => {
+ // Arrange β€” the shared client wraps a fetch failure in a plain Error that
+ // carries no response body.
+ vi.mocked(AgentServerConversationService.switchProfile).mockRejectedValue(
+ new Error("Request failed: Failed to fetch", {
+ cause: new TypeError("Failed to fetch"),
+ }),
+ );
+
+ // Act
+ const { result } = renderSwitchHook();
+ result.current.mutate({ conversationId: "conv-1", profileName: "Smart" });
+
+ // Assert
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(displayErrorToast).toHaveBeenCalledWith(
+ CORS_OR_NETWORK_ERROR_MESSAGE,
+ );
+ });
+
+ it("keeps the shared timeout wording when the switch request times out", async () => {
+ vi.mocked(AgentServerConversationService.switchProfile).mockRejectedValue(
+ new Error("Request timeout after 60000ms"),
+ );
+
+ const { result } = renderSwitchHook();
+ result.current.mutate({ conversationId: "conv-1", profileName: "Smart" });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(displayErrorToast).toHaveBeenCalledWith(
+ BACKEND_REQUEST_TIMEOUT_MESSAGE,
+ );
+ });
+
// The following behaviors run in the mutation-level onSuccess (not
// mutate-scoped callbacks) so they survive the switcher menu unmounting on
// select (#1571).
diff --git a/__tests__/utils/api-error-message.test.ts b/__tests__/utils/api-error-message.test.ts
index 9066ca07fa..5cfc4a177a 100644
--- a/__tests__/utils/api-error-message.test.ts
+++ b/__tests__/utils/api-error-message.test.ts
@@ -1,7 +1,14 @@
import { describe, expect, it } from "vitest";
import { AxiosError } from "axios";
import { HttpError } from "@openhands/typescript-client";
-import { getApiErrorMessage } from "#/utils/api-error-message";
+import {
+ getApiErrorMessage,
+ getApiOrConnectionErrorMessage,
+} from "#/utils/api-error-message";
+import {
+ BACKEND_REQUEST_TIMEOUT_MESSAGE,
+ CORS_OR_NETWORK_ERROR_MESSAGE,
+} from "#/utils/user-facing-error";
describe("getApiErrorMessage", () => {
it("returns the body `detail` from an HttpError when no `message` is present", () => {
@@ -16,6 +23,71 @@ describe("getApiErrorMessage", () => {
);
});
+ 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", {
+ detail: [
+ {
+ type: "string_too_long",
+ loc: ["body", "display_name"],
+ msg: "String should have at most 128 characters",
+ },
+ ],
+ });
+
+ // Act + Assert
+ expect(getApiErrorMessage(error, "fallback")).toBe(
+ "String should have at most 128 characters",
+ );
+ });
+
+ it("joins the `msg` fields of a FastAPI validation `detail` array, naming each field", () => {
+ // Arrange β€” Pydantic 422 bodies carry `detail` as a list of errors.
+ const error = new HttpError(422, "Unprocessable Entity", {
+ detail: [
+ {
+ type: "string_too_long",
+ loc: ["body", "display_name"],
+ msg: "String should have at most 128 characters",
+ },
+ { type: "missing", loc: ["body", "provider"], msg: "Field required" },
+ ],
+ });
+
+ // Act + Assert
+ expect(getApiErrorMessage(error, "fallback")).toBe(
+ "display_name: String should have at most 128 characters; provider: Field required",
+ );
+ });
+
+ it("returns a string `error` field from an HttpError body", () => {
+ // Arrange β€” some endpoints answer `{ error: "..." }` instead of `detail`.
+ const error = new HttpError(
+ 400,
+ "Bad Request",
+ { error: "Repository is not connected" },
+ 'HTTP request failed (400 Bad Request): {"error":"Repository is not connected"}',
+ );
+
+ // Act + Assert
+ expect(getApiErrorMessage(error, "fallback")).toBe(
+ "Repository is not connected",
+ );
+ });
+
+ it("returns the fallback instead of the raw transport text for an HttpError without a usable body", () => {
+ // Arrange β€” the client's message is `HTTP request failed (...): <json>`.
+ const error = new HttpError(
+ 500,
+ "Internal Server Error",
+ { unexpected: true },
+ 'HTTP request failed (500 Internal Server Error): {"unexpected":true}',
+ );
+
+ // Act + Assert
+ expect(getApiErrorMessage(error, "fallback")).toBe("fallback");
+ });
+
it("returns the response body `message` from an axios error", () => {
// Arrange β€” local agent-server calls still reject with AxiosError.
const error = new AxiosError("Request failed with status code 500");
@@ -32,3 +104,51 @@ describe("getApiErrorMessage", () => {
expect(getApiErrorMessage(null, "fallback")).toBe("fallback");
});
});
+
+describe("getApiOrConnectionErrorMessage", () => {
+ it("returns the server's `detail` for an HttpError", () => {
+ const error = new HttpError(404, "Not Found", {
+ detail: "Profile 'qa-nope' not found",
+ });
+
+ expect(getApiOrConnectionErrorMessage(error, "fallback")).toBe(
+ "Profile 'qa-nope' not found",
+ );
+ });
+
+ it("returns the fallback for an HttpError without a body", () => {
+ const error = new HttpError(
+ 502,
+ "Bad Gateway",
+ null,
+ "HTTP request failed (502 Bad Gateway): null",
+ );
+
+ expect(getApiOrConnectionErrorMessage(error, "fallback")).toBe("fallback");
+ });
+
+ it("keeps the shared disconnect wording for a network failure", () => {
+ // The shared client wraps fetch failures in a plain Error with no body.
+ const error = new Error("Request failed: Failed to fetch", {
+ cause: new TypeError("Failed to fetch"),
+ });
+
+ expect(getApiOrConnectionErrorMessage(error, "fallback")).toBe(
+ CORS_OR_NETWORK_ERROR_MESSAGE,
+ );
+ });
+
+ it("keeps the shared timeout wording when the request times out", () => {
+ const error = new Error("Request timeout after 60000ms");
+
+ expect(getApiOrConnectionErrorMessage(error, "fallback")).toBe(
+ BACKEND_REQUEST_TIMEOUT_MESSAGE,
+ );
+ });
+
+ it("returns the fallback when the error carries no usable information", () => {
+ expect(getApiOrConnectionErrorMessage(new Error(), "fallback")).toBe(
+ "fallback",
+ );
+ });
+});
diff --git a/src/api/agent-server-compatibility.ts b/src/api/agent-server-compatibility.ts
index 6e90268fbe..0ee3dab2b5 100644
--- a/src/api/agent-server-compatibility.ts
+++ b/src/api/agent-server-compatibility.ts
@@ -11,6 +11,7 @@ import {
isNoBackend,
} from "#/api/backend-registry/active-store";
import type { Backend } from "#/api/backend-registry/types";
+import { isSdkHttpError } from "#/utils/sdk-http-error";
import defaults from "../../config/defaults.json";
const AGENT_SERVER_INFO_TIMEOUT_MS = 5000;
@@ -148,14 +149,7 @@ export function getCachedAgentServerInfo(options?: {
return cachedAgentServerInfo;
}
-export function isSdkHttpError(error: unknown) {
- return (
- error instanceof Error &&
- error.name === "HttpError" &&
- "status" in error &&
- typeof error.status === "number"
- );
-}
+export { isSdkHttpError };
/**
* Narrows an SDK HTTP error to a specific status code.
diff --git a/src/components/features/settings/llm-profiles/rename-profile-modal.tsx b/src/components/features/settings/llm-profiles/rename-profile-modal.tsx
index 2127a20607..7129a3958a 100644
--- a/src/components/features/settings/llm-profiles/rename-profile-modal.tsx
+++ b/src/components/features/settings/llm-profiles/rename-profile-modal.tsx
@@ -10,6 +10,7 @@ import {
displayErrorToast,
displaySuccessToast,
} from "#/utils/custom-toast-handlers";
+import { getApiErrorMessage } from "#/utils/api-error-message";
import { I18nKey } from "#/i18n/declaration";
import { isProfileNameValid } from "#/utils/derive-profile-name";
@@ -53,9 +54,9 @@ export function RenameProfileModal({
);
onClose();
} catch (error) {
- const message =
- error instanceof Error ? error.message : t(I18nKey.ERROR$GENERIC);
- displayErrorToast(message);
+ // The agent-server refuses a duplicate name with a 409 whose `detail`
+ // names the conflict; show that instead of the raw transport text.
+ displayErrorToast(getApiErrorMessage(error, t(I18nKey.ERROR$GENERIC)));
}
};
diff --git a/src/hooks/mutation/use-manage-canvas-extensions.ts b/src/hooks/mutation/use-manage-canvas-extensions.ts
index 66caddd94d..b26d0aaae8 100644
--- a/src/hooks/mutation/use-manage-canvas-extensions.ts
+++ b/src/hooks/mutation/use-manage-canvas-extensions.ts
@@ -11,8 +11,7 @@ import {
displayErrorToast,
displaySuccessToast,
} from "#/utils/custom-toast-handlers";
-import { getApiErrorBody, getApiErrorMessage } from "#/utils/api-error-message";
-import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";
+import { getApiOrConnectionErrorMessage } from "#/utils/api-error-message";
function useInvalidateCanvasExtensions() {
const queryClient = useQueryClient();
@@ -25,11 +24,7 @@ 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(
- getApiErrorBody(error)
- ? getApiErrorMessage(error, fallback)
- : retrieveAxiosErrorMessage(error) || fallback,
- );
+ displayErrorToast(getApiOrConnectionErrorMessage(error, fallback));
}
export function useInstallCanvasExtension() {
diff --git a/src/hooks/mutation/use-switch-llm-profile.ts b/src/hooks/mutation/use-switch-llm-profile.ts
index d0efc5edc6..b00da3e2af 100644
--- a/src/hooks/mutation/use-switch-llm-profile.ts
+++ b/src/hooks/mutation/use-switch-llm-profile.ts
@@ -12,7 +12,7 @@ import {
stampActiveLlmProfile,
} from "#/hooks/chat/record-model-switch-message";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
-import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";
+import { getApiOrConnectionErrorMessage } from "#/utils/api-error-message";
import { I18nKey } from "#/i18n/declaration";
import { invalidateConversationQueries } from "./conversation-mutation-utils";
@@ -63,7 +63,9 @@ export const useSwitchLlmProfile = () => {
}),
onError: (error, { profileName }) => {
const fallback = t(I18nKey.MODEL$SWITCH_FAILED, { name: profileName });
- displayErrorToast(retrieveAxiosErrorMessage(error) || fallback);
+ // Server errors show their `detail`; a network failure or timeout keeps
+ // the shared "Disconnected (...)" wording.
+ displayErrorToast(getApiOrConnectionErrorMessage(error, fallback));
},
onSuccess: (_data, { conversationId, profileName }, context) => {
queryClient.invalidateQueries({
diff --git a/src/utils/api-error-message.ts b/src/utils/api-error-message.ts
index b927e51cca..ba0eac2e38 100644
--- a/src/utils/api-error-message.ts
+++ b/src/utils/api-error-message.ts
@@ -1,4 +1,6 @@
import axios from "axios";
+import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";
+import { isSdkHttpError } from "#/utils/sdk-http-error";
/**
* Extract the parsed response body from a failed API call.
@@ -16,23 +18,82 @@ export function getApiErrorBody(error: unknown): unknown {
return undefined;
}
+/** The last string segment of a validation error's `loc`, e.g. the field. */
+function getValidationField(loc: unknown): string | null {
+ if (!Array.isArray(loc)) return null;
+ const field = [...loc].reverse().find((part) => typeof part === "string");
+ return typeof field === "string" && field ? field : null;
+}
+
+/**
+ * Join the `msg` fields of a FastAPI/Pydantic validation `detail` array
+ * (`[{ loc, msg, type }, ...]`), or return null when there are none. With
+ * several errors each message is prefixed with its field so they can be
+ * told apart.
+ */
+function getValidationDetailMessage(detail: unknown): string | null {
+ if (!Array.isArray(detail)) return null;
+ const entries = detail
+ .filter(
+ (item): item is { loc?: unknown; msg: string } =>
+ !!item &&
+ typeof item === "object" &&
+ typeof (item as { msg?: unknown }).msg === "string" &&
+ (item as { msg: string }).msg !== "",
+ )
+ .map(({ loc, msg }) => ({ field: getValidationField(loc), msg }));
+ if (entries.length === 0) return null;
+ if (entries.length === 1) return entries[0].msg;
+ return entries
+ .map(({ field, msg }) => (field ? `${field}: ${msg}` : msg))
+ .join("; ");
+}
+
/**
* Extract a human-readable message from a failed API call. Prefers the
- * server-provided `message`/`detail` fields, then the `Error` message,
- * then `fallback`.
+ * 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
+ * (`HTTP request failed (status): {json}`), so it is never shown: an
+ * `HttpError` without a usable body yields `fallback`.
*/
export function getApiErrorMessage(error: unknown, fallback: string): string {
const body = getApiErrorBody(error);
if (body && typeof body === "object") {
- const { message, detail } = body as {
+ const {
+ message,
+ detail,
+ error: bodyError,
+ } = body as {
message?: 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;
+ if (typeof bodyError === "string" && bodyError) return bodyError;
}
+ if (isSdkHttpError(error)) return fallback;
if (error instanceof Error && error.message) return error.message;
return fallback;
}
+
+/**
+ * Like {@link getApiErrorMessage}, but a request that never got an answer
+ * (a network failure or timeout: no response body and no `HttpError`) keeps
+ * the shared "Disconnected (...)" wording instead of the client's raw
+ * `Request failed: ...` text.
+ */
+export function getApiOrConnectionErrorMessage(
+ error: unknown,
+ fallback: string,
+): string {
+ if (getApiErrorBody(error) || isSdkHttpError(error)) {
+ return getApiErrorMessage(error, fallback);
+ }
+ return retrieveAxiosErrorMessage(error) || fallback;
+}
diff --git a/src/utils/sdk-http-error.ts b/src/utils/sdk-http-error.ts
new file mode 100644
index 0000000000..daf471ad80
--- /dev/null
+++ b/src/utils/sdk-http-error.ts
@@ -0,0 +1,13 @@
+/**
+ * Whether `error` is the shared TypeScript client's `HttpError` (the server
+ * answered with a non-2xx status). Matches on shape rather than `instanceof`
+ * so it also recognizes errors from another copy of the client.
+ */
+export function isSdkHttpError(error: unknown) {
+ return (
+ error instanceof Error &&
+ error.name === "HttpError" &&
+ "status" in error &&
+ typeof error.status === "number"
+ );
+}