Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(home): show one error toast and keep the prompt when a launch fails (#17985)

Denis Ermakovd2c89252d26a
diff --git a/.pr/issue-17936/after-refused.png b/.pr/issue-17936/after-refused.png
new file mode 100644
index 0000000000..bb4b94dec1
Binary files /dev/null and b/.pr/issue-17936/after-refused.png differ
diff --git a/.pr/issue-17936/after-unreachable.png b/.pr/issue-17936/after-unreachable.png
new file mode 100644
index 0000000000..771a2ff781
Binary files /dev/null and b/.pr/issue-17936/after-unreachable.png differ
diff --git a/.pr/issue-17936/before-refused.png b/.pr/issue-17936/before-refused.png
new file mode 100644
index 0000000000..d490301b3f
Binary files /dev/null and b/.pr/issue-17936/before-refused.png differ
diff --git a/.pr/issue-17936/before-unreachable.png b/.pr/issue-17936/before-unreachable.png
new file mode 100644
index 0000000000..e91b769480
Binary files /dev/null and b/.pr/issue-17936/before-unreachable.png differ
diff --git a/__tests__/components/features/home/home-chat-launcher-failed-launch.test.tsx b/__tests__/components/features/home/home-chat-launcher-failed-launch.test.tsx
new file mode 100644
index 0000000000..77f75b39dc
--- /dev/null
+++ b/__tests__/components/features/home/home-chat-launcher-failed-launch.test.tsx
@@ -0,0 +1,232 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { QueryClientProvider } from "@tanstack/react-query";
+import toast, { Toaster } from "react-hot-toast";
+import { HttpError } from "@openhands/typescript-client";
+
+import { HomeChatLauncher } from "#/components/features/home/home-chat-launcher";
+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import AgentProfilesService from "#/api/agent-profiles-service/agent-profiles-service.api";
+import ProfilesService from "#/api/profiles-service/profiles-service.api";
+import WorkspacesService from "#/api/workspaces-service/workspaces-service.api";
+import { HOME_PROMPT_DRAFT_KEY } from "#/hooks/chat/use-draft-persistence";
+import { createAgentServerQueryClient } from "#/query-client-config";
+import { useConversationStore } from "#/stores/conversation-store";
+
+// The launch failure path is exercised end to end: the real composer, the real
+// conversation store, the real toast handlers and the app's query client (with
+// its global error toasts). Only the network-facing services are mocked.
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("#/context/navigation-context", () => ({
+ useNavigation: () => ({
+ currentPath: "/",
+ conversationId: null,
+ isNavigating: false,
+ navigate: vi.fn(),
+ }),
+}));
+
+vi.mock("#/contexts/active-backend-context", () => ({
+ useActiveBackend: () => ({
+ backend: {
+ id: "local-id",
+ name: "Local",
+ host: "http://localhost",
+ apiKey: "test",
+ kind: "local" as const,
+ },
+ orgId: null,
+ }),
+}));
+
+vi.mock("#/hooks/use-llm-configured", () => ({
+ useLlmConfigured: () => ({ isConfigured: true, isLoading: false }),
+}));
+
+vi.mock("#/hooks/query/use-conversation-workspace", () => ({
+ useConversationWorkspace: () => ({
+ isolated: false,
+ unsupportedMessage: null,
+ }),
+}));
+
+vi.mock("#/hooks/use-tracking", () => ({
+ useTracking: () => ({ trackConversationCreated: vi.fn() }),
+}));
+
+// The composer's model/profile controls and the automation sections below it
+// issue their own requests; none of them take part in launching.
+vi.mock("#/components/features/chat/components/chat-input-actions", () => ({
+ ChatInputActions: ({ handleSubmit }: { handleSubmit: () => void }) => (
+ <button type="button" data-testid="submit-button" onClick={handleSubmit} />
+ ),
+}));
+
+vi.mock(
+ "#/components/features/automations/recommended-automations-launcher",
+ () => ({ RecommendedAutomationsLauncher: () => null }),
+);
+
+vi.mock(
+ "#/components/features/home/featured-automations/pinned-automations-dashboard",
+ () => ({ PinnedAutomationsDashboard: () => null }),
+);
+
+vi.mock(
+ "#/components/features/home/featured-automations/running-automations-list",
+ () => ({ RunningAutomationsList: () => null }),
+);
+
+const PROMPT = "Refactor the billing module";
+const UNREACHABLE_MESSAGE =
+ 'HTTP request failed (502 Bad Gateway): "Bad Gateway: connect ECONNREFUSED 127.0.0.1:18811"';
+
+const unreachable = () =>
+ new HttpError(
+ 502,
+ "Bad Gateway",
+ "Bad Gateway: connect ECONNREFUSED 127.0.0.1:18811",
+ UNREACHABLE_MESSAGE,
+ );
+
+const renderLauncher = () =>
+ render(
+ <QueryClientProvider client={createAgentServerQueryClient()}>
+ <HomeChatLauncher />
+ <Toaster />
+ </QueryClientProvider>,
+ );
+
+// jsdom has no layout, so `innerText` (which the composer reads on submit) is
+// undefined; mirror `textContent` the way a browser would for plain text.
+const originalInnerText = Object.getOwnPropertyDescriptor(
+ HTMLElement.prototype,
+ "innerText",
+);
+
+async function submitPrompt() {
+ const input = await screen.findByTestId("chat-input");
+ input.textContent = PROMPT;
+ fireEvent.input(input);
+ await userEvent.setup().click(screen.getByTestId("submit-button"));
+ return input;
+}
+
+describe("HomeChatLauncher failed launch", () => {
+ beforeEach(() => {
+ Object.defineProperty(HTMLElement.prototype, "innerText", {
+ configurable: true,
+ get() {
+ return this.textContent ?? "";
+ },
+ set(value: string) {
+ this.textContent = value;
+ },
+ });
+ // <Toaster /> asks for the reduced-motion preference, which jsdom lacks.
+ vi.stubGlobal("matchMedia", vi.fn().mockReturnValue({ matches: true }));
+ vi.spyOn(WorkspacesService, "listWorkspaces").mockResolvedValue({
+ workspaces: [],
+ workspaceParents: [],
+ });
+ vi.spyOn(ProfilesService, "listProfiles").mockResolvedValue({
+ profiles: [],
+ active_profile: null,
+ } as never);
+ // The seeded OpenHands `default` profile makes the launch path revalidate
+ // the profile detail before it posts the conversation.
+ vi.spyOn(AgentProfilesService, "listProfiles").mockResolvedValue({
+ profiles: [
+ { id: "default-id", name: "default", agent_kind: "openhands" },
+ ],
+ active_agent_profile_id: "default-id",
+ } as never);
+ });
+
+ afterEach(() => {
+ if (originalInnerText) {
+ Object.defineProperty(
+ HTMLElement.prototype,
+ "innerText",
+ originalInnerText,
+ );
+ } else {
+ Reflect.deleteProperty(HTMLElement.prototype, "innerText");
+ }
+ toast.remove();
+ sessionStorage.removeItem(HOME_PROMPT_DRAFT_KEY);
+ useConversationStore.getState().clearMessageRestoreIfEmpty();
+ vi.restoreAllMocks();
+ });
+
+ it("shows one error toast, dismisses the loading toast and keeps the prompt when the agent server is unreachable", async () => {
+ // Arrange β€” every launch-path request fails the same way.
+ vi.spyOn(AgentProfilesService, "getProfile").mockRejectedValue(
+ unreachable(),
+ );
+ vi.spyOn(
+ AgentServerConversationService,
+ "createConversation",
+ ).mockRejectedValue(unreachable());
+ renderLauncher();
+
+ // Act
+ const input = await submitPrompt();
+
+ // Assert β€” the loading toast shows, then gives way to a single error.
+ // Error toasts outlive the loading toast's exit, so every one that was
+ // raised is still on screen when the loading toast is gone.
+ await screen.findByText("HOME$CREATING_CONVERSATION");
+ await waitFor(
+ () =>
+ expect(
+ screen.queryByText("HOME$CREATING_CONVERSATION"),
+ ).not.toBeInTheDocument(),
+ { timeout: 3000 },
+ );
+ expect(screen.getAllByText(UNREACHABLE_MESSAGE)).toHaveLength(1);
+ expect(input).toHaveTextContent(PROMPT);
+ });
+
+ it("names the missing MCP server in one readable toast and keeps the prompt when the launch is refused", async () => {
+ // Arrange β€” Agent Server's structured 422 for a dangling MCP server ref.
+ const detailMessage =
+ "MCP server ref(s) not present in the user's MCP config: 'qa_mcp_a'";
+ const body = {
+ detail: {
+ message: detailMessage,
+ dangling_mcp_server_refs: ["qa_mcp_a"],
+ },
+ };
+ vi.spyOn(AgentProfilesService, "getProfile").mockResolvedValue({
+ profile: { name: "default" },
+ } as never);
+ vi.spyOn(
+ AgentServerConversationService,
+ "createConversation",
+ ).mockRejectedValue(
+ new HttpError(
+ 422,
+ "Unprocessable Entity",
+ body,
+ `HTTP request failed (422 Unprocessable Entity): ${JSON.stringify(body)}`,
+ ),
+ );
+ renderLauncher();
+
+ // Act
+ const input = await submitPrompt();
+
+ // Assert
+ await waitFor(() =>
+ expect(screen.getAllByText(detailMessage)).toHaveLength(1),
+ );
+ expect(screen.queryByText(/dangling_mcp_server_refs/)).toBeNull();
+ expect(input).toHaveTextContent(PROMPT);
+ });
+});
diff --git a/__tests__/components/features/home/home-chat-launcher.test.tsx b/__tests__/components/features/home/home-chat-launcher.test.tsx
index a5c0994da0..cf20f0d5cf 100644
--- a/__tests__/components/features/home/home-chat-launcher.test.tsx
+++ b/__tests__/components/features/home/home-chat-launcher.test.tsx
@@ -17,6 +17,7 @@ const mockNavigate = vi.fn();
const mockUseActiveBackend = vi.fn();
const sendMessageWithAttachments = vi.fn();
const mockClearAllFiles = vi.fn();
+const mockRestoreMessageToInputIfEmpty = vi.fn();
const enqueueHomeTaskPendingMessage = vi.fn();
const mockDisplayErrorToast = vi.fn();
const mockUseLlmConfigured = vi.fn();
@@ -42,6 +43,7 @@ vi.mock("#/stores/conversation-store", () => ({
files: mockFiles,
imagesMarkedUploadAsFile: [],
clearAllFiles: mockClearAllFiles,
+ restoreMessageToInputIfEmpty: mockRestoreMessageToInputIfEmpty,
}),
}));
@@ -660,6 +662,32 @@ describe("HomeChatLauncher", () => {
);
});
+ it("does not hand the prompt back to a composer when a step after a successful create fails", async () => {
+ // Arrange β€” the conversation exists; only the follow-up enqueue fails.
+ mockUseActiveBackend.mockReturnValue(cloudBackend);
+ vi.spyOn(
+ AgentServerConversationService,
+ "createConversation",
+ ).mockResolvedValue(
+ makeConversationResponse({
+ id: "start-task-1",
+ app_conversation_id: null,
+ }),
+ );
+ enqueueHomeTaskPendingMessage.mockRejectedValue(new Error("Queue down"));
+
+ // Act
+ renderLauncher();
+ await userEvent.setup().click(screen.getByTestId("stub-chat-submit"));
+
+ // Assert β€” the prompt already belongs to the new conversation, so
+ // restoring it would replay it into that conversation's composer.
+ await waitFor(() =>
+ expect(mockDisplayErrorToast).toHaveBeenCalledWith("Queue down"),
+ );
+ expect(mockRestoreMessageToInputIfEmpty).not.toHaveBeenCalled();
+ });
+
it("defers attachments and enqueues an optimistic pending message for cloud start tasks", async () => {
mockUseActiveBackend.mockReturnValue(cloudBackend);
mockImages = [new File(["x"], "shot.png", { type: "image/png" })];
diff --git a/__tests__/utils/api-error-message.test.ts b/__tests__/utils/api-error-message.test.ts
index a51355164d..35262a97f6 100644
--- a/__tests__/utils/api-error-message.test.ts
+++ b/__tests__/utils/api-error-message.test.ts
@@ -23,29 +23,37 @@ describe("getApiErrorMessage", () => {
);
});
+ it("returns the nested `detail.message` when the body `detail` is structured", () => {
+ const error = new HttpError(422, "Unprocessable Entity", {
+ detail: {
+ message: "MCP server ref(s) not present: 'qa_mcp_a'",
+ dangling_mcp_server_refs: ["qa_mcp_a"],
+ },
+ });
+
+ expect(getApiErrorMessage(error, "fallback")).toBe(
+ "MCP server ref(s) not present: 'qa_mcp_a'",
+ );
+ });
+
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.",
);
diff --git a/src/components/features/home/home-chat-launcher.tsx b/src/components/features/home/home-chat-launcher.tsx
index f84654c1a3..ab50865864 100644
--- a/src/components/features/home/home-chat-launcher.tsx
+++ b/src/components/features/home/home-chat-launcher.tsx
@@ -1,5 +1,5 @@
import { useConversationWorkspace } from "#/hooks/query/use-conversation-workspace";
-import { useState } from "react";
+import { useEffect, useRef, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { CustomChatInput } from "#/components/features/chat/custom-chat-input";
@@ -25,6 +25,7 @@ import {
displayErrorToast,
TOAST_OPTIONS,
} from "#/utils/custom-toast-handlers";
+import { getApiErrorMessage } from "#/utils/api-error-message";
import { getWorkspacesUnsupportedMessage } from "#/utils/workspaces-compatibility";
import {
readStoredLocalWorkspaceMode,
@@ -60,9 +61,20 @@ export function HomeChatLauncher() {
);
const [selectedPlugins, setSelectedPlugins] = useState<PluginSpec[]>([]);
const [isPluginPickerOpen, setIsPluginPickerOpen] = useState(false);
+ const isMountedRef = useRef(true);
- const { mutateAsync: createConversation, isPending } =
- useCreateConversation();
+ useEffect(() => {
+ isMountedRef.current = true;
+ return () => {
+ isMountedRef.current = false;
+ };
+ }, []);
+
+ // The launcher reports a failed create itself (see handleSubmit), so the
+ // global mutation error toast is turned off to keep it to one toast.
+ const { mutateAsync: createConversation, isPending } = useCreateConversation({
+ disableToast: true,
+ });
const isCreatingElsewhere = useIsCreatingConversation();
const isCreating = isPending || isCreatingElsewhere;
const { isConfigured: isLlmConfigured, isLoading: isLlmConfigLoading } =
@@ -70,8 +82,13 @@ export function HomeChatLauncher() {
// Block sending entirely when there's no usable LLM; the banner above the
// launcher (rendered by the home route) explains it and offers setup.
const llmBlocked = !isLlmConfigLoading && !isLlmConfigured;
- const { images, files, imagesMarkedUploadAsFile, clearAllFiles } =
- useConversationStore();
+ const {
+ images,
+ files,
+ imagesMarkedUploadAsFile,
+ clearAllFiles,
+ restoreMessageToInputIfEmpty,
+ } = useConversationStore();
const { handleUpload } = useChatAttachmentUpload();
const { error: workspacesError } = useLocalWorkspaces({ enabled: isLocal });
const { isolated, unsupportedMessage: runtimeWorkspaceMessage } =
@@ -151,8 +168,10 @@ export function HomeChatLauncher() {
);
void (async () => {
+ let isCreated = false;
try {
const data = await createConversation(variables);
+ isCreated = true;
toast.dismiss(toastId);
try {
sessionStorage.removeItem(HOME_PROMPT_DRAFT_KEY);
@@ -224,7 +243,18 @@ export function HomeChatLauncher() {
navigate(`/conversations/${targetConversationId}`);
} catch (error) {
toast.dismiss(toastId);
- displayErrorToast(error instanceof Error ? error.message : null);
+ // Prefer the server's own message; without one, keep the launcher's
+ // existing wording (the error's message).
+ const fallback = error instanceof Error ? error.message : "";
+ displayErrorToast(getApiErrorMessage(error, fallback) || null);
+ // The composer cleared itself on submit; hand the prompt back so the
+ // user can retry without retyping it. Only when the create itself
+ // failed and this composer is still on screen: the request is consumed
+ // by whichever composer is mounted, so otherwise the prompt would
+ // replay into a conversation.
+ if (!isCreated && isMountedRef.current) {
+ restoreMessageToInputIfEmpty(message);
+ }
}
})();
};
diff --git a/src/hooks/chat/use-chat-input-logic.ts b/src/hooks/chat/use-chat-input-logic.ts
index 49e16366f2..77b25f9f52 100644
--- a/src/hooks/chat/use-chat-input-logic.ts
+++ b/src/hooks/chat/use-chat-input-logic.ts
@@ -48,15 +48,25 @@ export const useChatInputLogic = () => {
? rawMessageToSend
: null;
- // Restore a cancelled pending send back into the input only when empty.
+ // Restore a cancelled pending send (or, on the home page, a prompt whose
+ // launch failed) back into the input only when empty.
useEffect(() => {
- if (!conversationId || !messageRestoreIfEmpty) {
+ if (!messageRestoreIfEmpty) {
return;
}
- const currentText = getTextContent(chatInputRef.current).trim();
+ const element = chatInputRef.current;
+ const currentText = getTextContent(element).trim();
if (currentText.length === 0) {
- setMessageToSend(messageRestoreIfEmpty.text);
+ if (conversationId) {
+ setMessageToSend(messageRestoreIfEmpty.text);
+ } else if (element) {
+ // Write the text directly rather than queueing it as messageToSend:
+ // the input event runs the same path as typing (resize, draft save
+ // and submit-button state).
+ element.textContent = messageRestoreIfEmpty.text;
+ element.dispatchEvent(new InputEvent("input", { bubbles: true }));
+ }
}
clearMessageRestoreIfEmpty();
}, [
diff --git a/src/hooks/mutation/use-create-conversation.ts b/src/hooks/mutation/use-create-conversation.ts
index 6b5c3cb85b..25a3eab79c 100644
--- a/src/hooks/mutation/use-create-conversation.ts
+++ b/src/hooks/mutation/use-create-conversation.ts
@@ -61,7 +61,17 @@ interface CreateConversationResponse {
task_id?: string;
}
-export const useCreateConversation = () => {
+interface UseCreateConversationOptions {
+ /**
+ * Set by callers that report a failed create themselves, so the global
+ * mutation error toast doesn't repeat it.
+ */
+ disableToast?: boolean;
+}
+
+export const useCreateConversation = ({
+ disableToast = false,
+}: UseCreateConversationOptions = {}) => {
const queryClient = useQueryClient();
const { trackConversationCreated } = useTracking();
// Cache-warm on the home page (the profile picker reads the same query).
@@ -88,6 +98,7 @@ export const useCreateConversation = () => {
return useMutation({
mutationKey: CREATE_CONVERSATION_MUTATION_KEY,
+ meta: { disableToast },
mutationFn: async (
variables: CreateConversationVariables,
): Promise<CreateConversationResponse> => {
@@ -115,6 +126,9 @@ export const useCreateConversation = () => {
queryKey: [...AGENT_PROFILES_QUERY_KEYS.all, backend.id, orgId],
queryFn: AgentProfilesService.listProfiles,
...AGENT_PROFILES_RETRY_OPTIONS,
+ // A failure here rejects the mutation, which reports it; a query
+ // toast on top would show the same error twice.
+ meta: { disableToast: true },
});
const requestedAgentProfileId =
@@ -184,6 +198,8 @@ export const useCreateConversation = () => {
// errors, fall back to agent_settings immediately rather than
// stalling the send through the default exponential backoff.
retry: false,
+ // Handled by the fallback below, so there is nothing to report.
+ meta: { disableToast: true },
});
llmProfileExists = llm.profiles.some(
(profile) => profile.name === resolvedAgentProfile.llm_profile_ref,
@@ -244,6 +260,8 @@ export const useCreateConversation = () => {
queryFn: () =>
AgentProfilesService.getProfile(resolvedAgentProfile.name),
...AGENT_PROFILES_RETRY_OPTIONS,
+ // Handled by failing closed below, so there is nothing to report.
+ meta: { disableToast: true },
});
const secretRefs = (detail.profile as { secret_refs?: unknown })
.secret_refs;
diff --git a/src/utils/api-error-message.ts b/src/utils/api-error-message.ts
index 53dca51e94..428febccdb 100644
--- a/src/utils/api-error-message.ts
+++ b/src/utils/api-error-message.ts
@@ -59,11 +59,11 @@ const AGENT_SERVER_GENERIC_DETAIL = "Internal Server Error";
/**
* Extract a human-readable message from a failed API call. Prefers the
* 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
+ * FastAPI validation `detail` array and a structured `detail.message`), 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`.
*/
@@ -83,10 +83,19 @@ export function getApiErrorMessage(error: unknown, fallback: string): string {
error?: unknown;
};
if (typeof message === "string" && message) return message;
+ const validationMessage = getValidationDetailMessage(detail);
+ const structuredDetailMessage =
+ detail && typeof detail === "object" && !Array.isArray(detail)
+ ? (detail as { message?: unknown }).message
+ : undefined;
const detailMessage =
typeof detail === "string" && detail
? detail
- : getValidationDetailMessage(detail);
+ : validationMessage ||
+ (typeof structuredDetailMessage === "string" &&
+ structuredDetailMessage
+ ? structuredDetailMessage
+ : undefined);
if (
typeof exception === "string" &&
exception &&