🙌 OpenHands: AI-Driven Development
fix(conversation-panel): report download failures once and select Recent by default (#18021)
Engel Nyst1413ebe84711
diff --git a/__tests__/components/features/conversation-panel/conversation-card.test.tsx b/__tests__/components/features/conversation-panel/conversation-card.test.tsxindex c6dee95368..f00d9426a8 100644--- a/__tests__/components/features/conversation-panel/conversation-card.test.tsx+++ b/__tests__/components/features/conversation-panel/conversation-card.test.tsx@@ -24,6 +24,7 @@ import {import type { Backend } from "#/api/backend-registry/types";import { ActiveBackendProvider } from "#/contexts/active-backend-context";import { useFreeModelsStore } from "#/stores/free-models-store";+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";// We'll use the actual i18next implementation but override the translation function@@ -55,6 +56,7 @@ vi.mock("react-i18next", async () => {vi.mock("#/hooks/use-tracking", () => ({useTracking: () => ({trackDownloadVsCodeButtonClicked: vi.fn(),+ trackDownloadTrajectoryButtonClicked: vi.fn(),}),}));@@ -413,6 +415,36 @@ describe("ConversationCard", () => {expect(onContextMenuToggle).toHaveBeenCalledWith(false);});+ it("closes the context menu when downloading the conversation fails", async () => {+ const user = userEvent.setup();+ const onContextMenuToggle = vi.fn();+ vi.spyOn(+ AgentServerConversationService,+ "downloadConversation",+ ).mockRejectedValue(new Error("HTTP request failed (502 Bad Gateway)"));+ renderWithProviders(+ <ConversationCard+ conversationId="conv-1"+ onDelete={onDelete}+ title="Conversation 1"+ selectedRepository={null}+ lastUpdatedAt="2021-10-01T12:00:00Z"+ contextMenuOpen+ onContextMenuToggle={onContextMenuToggle}+ />,+ );++ await user.click(+ within(screen.getByTestId("context-menu")).getByTestId(+ "download-trajectory-button",+ ),+ );++ await vi.waitFor(() =>+ expect(onContextMenuToggle).toHaveBeenCalledWith(false),+ );+ });+test("clicking the selectedRepository should not trigger the onClick handler", async () => {const user = userEvent.setup();renderWithProviders(diff --git a/__tests__/components/features/conversation-panel/conversation-layouts-menu.test.tsx b/__tests__/components/features/conversation-panel/conversation-layouts-menu.test.tsxindex 1c666860e2..59dcd60520 100644--- a/__tests__/components/features/conversation-panel/conversation-layouts-menu.test.tsx+++ b/__tests__/components/features/conversation-panel/conversation-layouts-menu.test.tsx@@ -81,9 +81,10 @@ describe("ConversationLayoutsMenu", () => {).toBe(true);await user.click(screen.getByTestId("layout-preset-recent-activity"));- expect(- screen.getByTestId("layout-preset-recent-activity"),- ).toHaveAttribute("aria-checked", "true");+ expect(screen.getByTestId("layout-preset-recent-activity")).toHaveAttribute(+ "aria-checked",+ "true",+ );await user.click(screen.getByTestId("layout-preset-by-workspace"));expect(screen.getByTestId("layout-preset-by-workspace")).toHaveAttribute(@@ -92,9 +93,40 @@ describe("ConversationLayoutsMenu", () => {);});+ it("selects a preset for the untouched default and reads Custom after one deviation", async () => {+ const user = userEvent.setup();+ useConversationPanelPreferencesStore.setState(+ useConversationPanelPreferencesStore.getInitialState(),+ );+ renderMenu();++ const checkedPresets = screen+ .getAllByRole("menuitemradio")+ .filter((row) => row.getAttribute("aria-checked") === "true");+ expect(checkedPresets).toEqual([+ screen.getByTestId("layout-preset-recent-activity"),+ ]);+ expect(screen.getByTestId("advanced-options-row")).not.toHaveTextContent(+ "CONVERSATION_PANEL$ADVANCED_OPTIONS_CUSTOM",+ );++ await user.click(screen.getByTestId("advanced-options-row"));+ await user.click(screen.getByTestId("toggle-hover-metadata"));+ await user.click(screen.getByTestId("advanced-options-close"));++ expect(+ screen+ .getAllByRole("menuitemradio")+ .filter((row) => row.getAttribute("aria-checked") === "true"),+ ).toHaveLength(0);+ expect(screen.getByTestId("advanced-options-row")).toHaveTextContent(+ "CONVERSATION_PANEL$ADVANCED_OPTIONS_CUSTOM",+ );+ });+it("labels the Advanced options row Custom when no preset matches", async () => {- // Matches no preset: the chronological presets all hide older- // conversations, and by-workspace requires grouped mode.+ // Matches no preset: Recent shows every thread, Active and Compact hide+ // older conversations, and by-workspace requires grouped mode.useConversationPanelPreferencesStore.getState().applyLayoutSettings({organizeMode: "chronological",conversationSort: "updated",diff --git a/__tests__/hooks/use-conversation-name-context-menu.test.tsx b/__tests__/hooks/use-conversation-name-context-menu.test.tsxindex 9dfeebc8c8..fd0ac9bc69 100644--- a/__tests__/hooks/use-conversation-name-context-menu.test.tsx+++ b/__tests__/hooks/use-conversation-name-context-menu.test.tsx@@ -393,6 +393,25 @@ describe("useConversationNameContextMenu", () => {expect(harness.navigate).toHaveBeenCalledWith("/conversations");});+ it("closes the menu without rethrowing when the download fails", async () => {+ harness.downloadConversation.mockRejectedValue(+ new Error("HTTP request failed (502 Bad Gateway)"),+ );+ const onContextMenuToggle = vi.fn();+ const { result } = renderHook(() =>+ useConversationNameContextMenu({+ conversationId: "conv-active",+ onContextMenuToggle,+ }),+ );++ await act(async () =>+ result.current.handleDownloadConversation(clickEvent().event),+ );++ expect(onContextMenuToggle).toHaveBeenCalledWith(false);+ });+it("does not navigate after deleting a conversation that is not currently open", () => {harness.currentConversationId = "conv-current";const { result } = renderHook(() =>diff --git a/__tests__/hooks/use-download-conversation.test.ts b/__tests__/hooks/use-download-conversation.test.tsindex 85e10d8aeb..b3b9c7afa2 100644--- a/__tests__/hooks/use-download-conversation.test.ts+++ b/__tests__/hooks/use-download-conversation.test.ts@@ -7,12 +7,16 @@ import AgentServerConversationService from "#/api/conversation-service/agent-serconst trackDownloadTrajectoryButtonClickedMock = vi.fn();vi.mock("#/hooks/use-tracking", () => ({useTracking: () => ({- trackDownloadTrajectoryButtonClicked: trackDownloadTrajectoryButtonClickedMock,+ trackDownloadTrajectoryButtonClicked:+ trackDownloadTrajectoryButtonClickedMock,}),}));vi.mock("react-i18next", () => ({- useTranslation: () => ({ t: (key: string) => key }),+ useTranslation: () => ({+ t: (key: string, options?: { error?: string }) =>+ options?.error ? `${key}: ${options.error}` : key,+ }),}));vi.mock("#/utils/utils", () => ({@@ -24,6 +28,8 @@ vi.mock("#/utils/custom-toast-handlers", () => ({}));import { useDownloadConversation } from "#/hooks/use-download-conversation";+import { createAgentServerQueryClient } from "#/query-client-config";+import { displayErrorToast } from "#/utils/custom-toast-handlers";const createWrapper = () => {const queryClient = new QueryClient({@@ -94,3 +100,33 @@ describe("useDownloadConversation - tracking", () => {expect(trackDownloadTrajectoryButtonClickedMock).toHaveBeenCalledTimes(1);});});++describe("useDownloadConversation - failure", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("shows exactly one toast naming the download failure and its cause", async () => {+ vi.spyOn(+ AgentServerConversationService,+ "downloadConversation",+ ).mockRejectedValue(new Error("connect ECONNREFUSED 127.0.0.1:18831"));+ // The app's real client, so the global MutationCache toast is in play.+ const queryClient = createAgentServerQueryClient();+ const { result } = renderHook(() => useDownloadConversation(), {+ wrapper: ({ children }: { children: React.ReactNode }) =>+ React.createElement(+ QueryClientProvider,+ { client: queryClient },+ children,+ ),+ });++ await expect(result.current.mutateAsync("conv-123")).rejects.toThrow();++ expect(displayErrorToast).toHaveBeenCalledTimes(1);+ expect(displayErrorToast).toHaveBeenCalledWith(+ "CONVERSATION$DOWNLOAD_ERROR: connect ECONNREFUSED 127.0.0.1:18831",+ );+ });+});diff --git a/src/components/features/conversation-panel/conversation-card/conversation-card.tsx b/src/components/features/conversation-panel/conversation-card/conversation-card.tsxindex a25e3576a0..7410d6a8b1 100644--- a/src/components/features/conversation-panel/conversation-card/conversation-card.tsx+++ b/src/components/features/conversation-panel/conversation-card/conversation-card.tsx@@ -191,7 +191,12 @@ export function ConversationCard({event.stopPropagation();if (conversationId) {- await downloadConversation(conversationId);+ try {+ await downloadConversation(conversationId);+ } catch {+ // useDownloadConversation already showed the error toast; close the+ // menu as on success instead of leaking the rejection.+ }}onContextMenuToggle?.(false);};diff --git a/src/components/features/conversation-panel/conversation-layouts-menu.tsx b/src/components/features/conversation-panel/conversation-layouts-menu.tsxindex f33cb38340..506c2b3ed6 100644--- a/src/components/features/conversation-panel/conversation-layouts-menu.tsx+++ b/src/components/features/conversation-panel/conversation-layouts-menu.tsx@@ -57,10 +57,9 @@ const LAYOUT_PRESETS: LayoutPreset[] = [id: "recent-activity",icon: Clock3,labelKey: I18nKey.CONVERSATION_PANEL$LAYOUT_RECENT_ACTIVITY,- settings: {- ...DEFAULT_LAYOUT_SETTINGS,- showOlderConversations: false,- },+ // Exactly the default bundle, so a profile that never changed a layout+ // preference reads as Recent rather than Custom.+ settings: DEFAULT_LAYOUT_SETTINGS,},{id: "focused",diff --git a/src/hooks/use-conversation-name-context-menu.ts b/src/hooks/use-conversation-name-context-menu.tsindex 533646813f..c4224882f1 100644--- a/src/hooks/use-conversation-name-context-menu.ts+++ b/src/hooks/use-conversation-name-context-menu.ts@@ -106,7 +106,12 @@ export function useConversationNameContextMenu({event.preventDefault();event.stopPropagation();if (conversationId) {- await downloadConversation(conversationId);+ try {+ await downloadConversation(conversationId);+ } catch {+ // useDownloadConversation already showed the error toast; close the+ // menu as on success instead of leaking the rejection.+ }}onContextMenuToggle?.(false);};diff --git a/src/hooks/use-download-conversation.ts b/src/hooks/use-download-conversation.tsindex bb4a2d1fbb..fb3df35f19 100644--- a/src/hooks/use-download-conversation.ts+++ b/src/hooks/use-download-conversation.ts@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import { downloadBlob } from "#/utils/utils";import { displayErrorToast } from "#/utils/custom-toast-handlers";+import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";import { I18nKey } from "#/i18n/declaration";export const useDownloadConversation = () => {@@ -20,8 +21,15 @@ export const useDownloadConversation = () => {);downloadBlob(blob, `conversation_${conversationId}.zip`);},- onError: () => {- displayErrorToast(t(I18nKey.CONVERSATION$DOWNLOAD_ERROR));+ // onError below is the only toast for a failed download; without this the+ // global MutationCache handler adds a second, raw HTTP-error toast.+ meta: { disableToast: true },+ onError: (error) => {+ displayErrorToast(+ t(I18nKey.CONVERSATION$DOWNLOAD_ERROR, {+ error: retrieveAxiosErrorMessage(error) || t(I18nKey.ERROR$GENERIC),+ }),+ );},});};diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 36e523e1c3..041dd8942b 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -21046,21 +21046,21 @@"ca": "No hi ha dades de mètriques disponibles"},"CONVERSATION$DOWNLOAD_ERROR": {- "en": "ConversationId unknown, cannot download trajectory",- "ja": "会話IDが不明です。軌跡をダウンロードできません",- "zh-CN": "会话ID未知,无法下载轨迹",- "zh-TW": "對話ID未知,無法下載軌跡",- "ko-KR": "대화 ID를 알 수 없어 궤적을 다운로드할 수 없습니다",- "de": "Gesprächs-ID unbekannt, Trajektorie kann nicht heruntergeladen werden",- "no": "Samtale-ID ukjent, kan ikke laste ned bane",- "it": "ID conversazione sconosciuto, impossibile scaricare la traiettoria",- "pt": "ID de conversa desconhecido, não é possível baixar a trajetória",- "es": "ID de conversación desconocido, no se puede descargar la trayectoria",- "ar": "معرف المحادثة غير معروف، لا يمكن تنزيل المسار",- "fr": "ID de conversation inconnu, impossible de télécharger la trajectoire",- "tr": "Konuşma kimliği bilinmiyor, yörünge indirilemiyor",- "uk": "Ідентифікатор розмови невідомий, неможливо завантажити траєкторію",- "ca": "ConversationId desconegut, no es pot descarregar la trajectòria"+ "en": "Couldn't download the conversation data: {{error}}",+ "ja": "会話データをダウンロードできませんでした: {{error}}",+ "zh-CN": "无法下载会话数据:{{error}}",+ "zh-TW": "無法下載對話資料:{{error}}",+ "ko-KR": "대화 데이터를 다운로드할 수 없습니다: {{error}}",+ "de": "Die Gesprächsdaten konnten nicht heruntergeladen werden: {{error}}",+ "no": "Kunne ikke laste ned samtaledataene: {{error}}",+ "it": "Impossibile scaricare i dati della conversazione: {{error}}",+ "pt": "Não foi possível baixar os dados da conversa: {{error}}",+ "es": "No se pudieron descargar los datos de la conversación: {{error}}",+ "ar": "تعذّر تنزيل بيانات المحادثة: {{error}}",+ "fr": "Impossible de télécharger les données de la conversation : {{error}}",+ "tr": "Konuşma verileri indirilemedi: {{error}}",+ "uk": "Не вдалося завантажити дані розмови: {{error}}",+ "ca": "No s'han pogut descarregar les dades de la conversa: {{error}}"},"CONVERSATION$UPDATED": {"en": ", updated",