π OpenHands: AI-Driven Development
fix: clean up conversation localStorage on delete and migration (#12300)
Mohammed Abdulai3cb76f5cbb17
diff --git a/frontend/__tests__/components/features/conversation/conversation-tabs-context-menu.test.tsx b/frontend/__tests__/components/features/conversation/conversation-tabs-context-menu.test.tsxdeleted file mode 100644index 2a7aa747be..0000000000--- a/frontend/__tests__/components/features/conversation/conversation-tabs-context-menu.test.tsx+++ /dev/null@@ -1,82 +0,0 @@-import { describe, it, expect, afterEach } from "vitest";-import { render, screen } from "@testing-library/react";-import userEvent from "@testing-library/user-event";-import { MemoryRouter, Route, Routes } from "react-router";-import { ConversationTabsContextMenu } from "#/components/features/conversation/conversation-tabs/conversation-tabs-context-menu";--function renderWithRouter(conversationId: string, onClose: () => void) {- return render(- <MemoryRouter initialEntries={[`/conversations/${conversationId}`]}>- <Routes>- <Route- path="/conversations/:conversationId"- element={<ConversationTabsContextMenu isOpen onClose={onClose} />}- />- </Routes>- </MemoryRouter>,- );-}--describe("ConversationTabsContextMenu", () => {- afterEach(() => {- localStorage.clear();- });-- it("should use per-conversation localStorage key for unpinned tabs", async () => {- const user = userEvent.setup();- const onClose = () => {};-- // Render for conversation-1- const { unmount } = renderWithRouter("conversation-1", onClose);-- // Unpin the terminal tab in conversation-1- const terminalItem = screen.getByText("COMMON$TERMINAL");- await user.click(terminalItem);-- // Verify localStorage key is per-conversation- const stored1 = JSON.parse(- localStorage.getItem("conversation-unpinned-tabs-conversation-1") || "[]",- );- expect(stored1).toContain("terminal");-- unmount();-- // Switch to conversation-2- renderWithRouter("conversation-2", onClose);-- // conversation-2 should have its own empty state- const stored2 = JSON.parse(- localStorage.getItem("conversation-unpinned-tabs-conversation-2") || "[]",- );- expect(stored2).toEqual([]);-- // conversation-1 state should still have terminal unpinned- const stored1Again = JSON.parse(- localStorage.getItem("conversation-unpinned-tabs-conversation-1") || "[]",- );- expect(stored1Again).toContain("terminal");- });-- it("should toggle tab pin state when clicked", async () => {- const user = userEvent.setup();- const onClose = () => {};-- renderWithRouter("conversation-1", onClose);-- const terminalItem = screen.getByText("COMMON$TERMINAL");-- // Click to unpin- await user.click(terminalItem);- let stored = JSON.parse(- localStorage.getItem("conversation-unpinned-tabs-conversation-1") || "[]",- );- expect(stored).toContain("terminal");-- // Click again to pin- await user.click(terminalItem);- stored = JSON.parse(- localStorage.getItem("conversation-unpinned-tabs-conversation-1") || "[]",- );- expect(stored).not.toContain("terminal");- });-});diff --git a/frontend/__tests__/components/features/conversation/conversation-tabs.test.tsx b/frontend/__tests__/components/features/conversation/conversation-tabs.test.tsxnew file mode 100644index 0000000000..58af4ff491--- /dev/null+++ b/frontend/__tests__/components/features/conversation/conversation-tabs.test.tsx@@ -0,0 +1,90 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, it, expect, vi, beforeEach } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { MemoryRouter } from "react-router";+import { ConversationTabs } from "#/components/features/conversation/conversation-tabs/conversation-tabs";+import { ConversationTabsContextMenu } from "#/components/features/conversation/conversation-tabs/conversation-tabs-context-menu";++const TASK_CONVERSATION_ID = "task-ec03fb2ab8604517b24af632b058c2fd";+const REAL_CONVERSATION_ID = "conv-abc123";++vi.mock("#/utils/feature-flags", () => ({+ USE_PLANNING_AGENT: () => false,+}));++let mockConversationId = TASK_CONVERSATION_ID;++vi.mock("#/hooks/use-conversation-id", () => ({+ useConversationId: () => ({ conversationId: mockConversationId }),+}));++const createWrapper = (conversationId: string) => {+ return ({ children }: { children: React.ReactNode }) => (+ <MemoryRouter initialEntries={[`/conversations/${conversationId}`]}>+ <QueryClientProvider client={new QueryClient()}>+ {children}+ </QueryClientProvider>+ </MemoryRouter>+ );+};++describe("ConversationTabs localStorage behavior", () => {+ beforeEach(() => {+ localStorage.clear();+ vi.resetAllMocks();+ mockConversationId = TASK_CONVERSATION_ID;+ });++ describe("task-prefixed conversation IDs", () => {+ it("should not create localStorage entries for task-prefixed conversation IDs", () => {+ render(<ConversationTabs />, {+ wrapper: createWrapper(TASK_CONVERSATION_ID),+ });++ expect(+ localStorage.getItem(`conversation-state-${TASK_CONVERSATION_ID}`),+ ).toBeNull();+ });+ });++ describe("consolidated localStorage key", () => {+ it("should use a single consolidated key for tab state", async () => {+ mockConversationId = REAL_CONVERSATION_ID;+ const user = userEvent.setup();++ render(<ConversationTabs />, {+ wrapper: createWrapper(REAL_CONVERSATION_ID),+ });++ const changesTab = screen.getByText("COMMON$CHANGES");+ await user.click(changesTab);++ const consolidatedKey = `conversation-state-${REAL_CONVERSATION_ID}`;+ const storedState = localStorage.getItem(consolidatedKey);+ expect(storedState).not.toBeNull();++ const parsed = JSON.parse(storedState!);+ expect(parsed).toHaveProperty("selectedTab");+ expect(parsed).toHaveProperty("rightPanelShown");+ expect(parsed).toHaveProperty("unpinnedTabs");+ });++ it("should store unpinned tabs in consolidated key via context menu", async () => {+ mockConversationId = REAL_CONVERSATION_ID;+ const user = userEvent.setup();++ render(<ConversationTabsContextMenu isOpen={true} onClose={vi.fn()} />);++ const terminalItem = screen.getByText("COMMON$TERMINAL");+ await user.click(terminalItem);++ const consolidatedKey = `conversation-state-${REAL_CONVERSATION_ID}`;+ const storedState = localStorage.getItem(consolidatedKey);+ expect(storedState).not.toBeNull();++ const parsed = JSON.parse(storedState!);+ expect(parsed.unpinnedTabs).toContain("terminal");+ });+ });+});diff --git a/frontend/__tests__/conversation-local-storage.test.ts b/frontend/__tests__/conversation-local-storage.test.tsnew file mode 100644index 0000000000..b671be114a--- /dev/null+++ b/frontend/__tests__/conversation-local-storage.test.ts@@ -0,0 +1,38 @@+import { describe, it, expect, beforeEach, vi } from "vitest";+import {+ clearConversationLocalStorage,+ LOCAL_STORAGE_KEYS,+} from "#/utils/conversation-local-storage";++describe("conversation localStorage utilities", () => {+ beforeEach(() => {+ localStorage.clear();+ });++ describe("clearConversationLocalStorage", () => {+ it("removes the consolidated conversation-state localStorage entry", () => {+ const conversationId = "conv-123";++ // Set up the consolidated key+ const consolidatedKey = `${LOCAL_STORAGE_KEYS.CONVERSATION_STATE}-${conversationId}`;+ localStorage.setItem(+ consolidatedKey,+ JSON.stringify({+ selectedTab: "editor",+ rightPanelShown: true,+ unpinnedTabs: [],+ }),+ );++ clearConversationLocalStorage(conversationId);++ expect(localStorage.getItem(consolidatedKey)).toBeNull();+ });++ it("does not throw if conversation keys do not exist", () => {+ expect(() => {+ clearConversationLocalStorage("non-existent-id");+ }).not.toThrow();+ });+ });+});diff --git a/frontend/src/components/features/conversation/conversation-tabs/conversation-tabs-context-menu.tsx b/frontend/src/components/features/conversation/conversation-tabs/conversation-tabs-context-menu.tsxindex a47dd40e0d..a5f9b794b8 100644--- a/frontend/src/components/features/conversation/conversation-tabs/conversation-tabs-context-menu.tsx+++ b/frontend/src/components/features/conversation/conversation-tabs/conversation-tabs-context-menu.tsx@@ -1,8 +1,9 @@import { useTranslation } from "react-i18next";-import { useLocalStorage } from "@uidotdev/usehooks";import { ContextMenu } from "#/ui/context-menu";import { ContextMenuListItem } from "../../context-menu/context-menu-list-item";import { useClickOutsideElement } from "#/hooks/use-click-outside-element";+import { useConversationId } from "#/hooks/use-conversation-id";+import { useConversationLocalStorageState } from "#/utils/conversation-local-storage";import { I18nKey } from "#/i18n/declaration";import TerminalIcon from "#/icons/terminal.svg?react";import GlobeIcon from "#/icons/globe.svg?react";@@ -13,7 +14,6 @@ import PillIcon from "#/icons/pill.svg?react";import PillFillIcon from "#/icons/pill-fill.svg?react";import { USE_PLANNING_AGENT } from "#/utils/feature-flags";import LessonPlanIcon from "#/icons/lesson-plan.svg?react";-import { useConversationId } from "#/hooks/use-conversation-id";interface ConversationTabsContextMenuProps {isOpen: boolean;@@ -27,11 +27,8 @@ export function ConversationTabsContextMenu({const ref = useClickOutsideElement<HTMLUListElement>(onClose);const { t } = useTranslation();const { conversationId } = useConversationId();-- const [unpinnedTabs, setUnpinnedTabs] = useLocalStorage<string[]>(- `conversation-unpinned-tabs-${conversationId}`,- [],- );+ const { state, setUnpinnedTabs } =+ useConversationLocalStorageState(conversationId);const shouldUsePlanningAgent = USE_PLANNING_AGENT();@@ -54,11 +51,11 @@ export function ConversationTabsContextMenu({if (!isOpen) return null;const handleTabClick = (tab: string) => {- setUnpinnedTabs((prev) =>- prev.includes(tab)- ? prev.filter((tabItem) => tabItem !== tab)- : [...prev, tab],- );+ if (state.unpinnedTabs.includes(tab)) {+ setUnpinnedTabs(state.unpinnedTabs.filter((item) => item !== tab));+ } else {+ setUnpinnedTabs([...state.unpinnedTabs, tab]);+ }};return (@@ -69,7 +66,7 @@ export function ConversationTabsContextMenu({className="mt-2 w-fit z-[9999]">{tabConfig.map(({ tab, icon: Icon, i18nKey }) => {- const pinned = !unpinnedTabs.includes(tab);+ const pinned = !state.unpinnedTabs.includes(tab);return (<ContextMenuListItemkey={tab}diff --git a/frontend/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx b/frontend/src/components/features/conversation/conversation-tabs/conversation-tabs.tsxindex ed649f373c..f9db19819d 100644--- a/frontend/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx+++ b/frontend/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx@@ -1,6 +1,5 @@import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";-import { useLocalStorage } from "@uidotdev/usehooks";import TerminalIcon from "#/icons/terminal.svg?react";import GlobeIcon from "#/icons/globe.svg?react";import ServerIcon from "#/icons/server.svg?react";@@ -9,6 +8,7 @@ import VSCodeIcon from "#/icons/vscode.svg?react";import ThreeDotsVerticalIcon from "#/icons/three-dots-vertical.svg?react";import LessonPlanIcon from "#/icons/lesson-plan.svg?react";import { cn } from "#/utils/utils";+import { useConversationLocalStorageState } from "#/utils/conversation-local-storage";import { ConversationTabNav } from "./conversation-tab-nav";import { ChatActionTooltip } from "../../chat/chat-action-tooltip";import { I18nKey } from "#/i18n/declaration";@@ -32,23 +32,11 @@ export function ConversationTabs() {const [isMenuOpen, setIsMenuOpen] = useState(false);- // Persist selectedTab and isRightPanelShown in localStorage per conversation- const [persistedSelectedTab, setPersistedSelectedTab] =- useLocalStorage<ConversationTab | null>(- `conversation-selected-tab-${conversationId}`,- "editor",- );-- const [persistedIsRightPanelShown, setPersistedIsRightPanelShown] =- useLocalStorage<boolean>(- `conversation-right-panel-shown-${conversationId}`,- true,- );-- const [persistedUnpinnedTabs] = useLocalStorage<string[]>(- `conversation-unpinned-tabs-${conversationId}`,- [],- );+ const {+ state: persistedState,+ setSelectedTab: setPersistedSelectedTab,+ setRightPanelShown: setPersistedRightPanelShown,+ } = useConversationLocalStorageState(conversationId);const shouldUsePlanningAgent = USE_PLANNING_AGENT();@@ -61,13 +49,13 @@ export function ConversationTabs() {// Initialize Zustand state from localStorage on component mountuseEffect(() => {// Initialize selectedTab from localStorage if available- setSelectedTab(persistedSelectedTab);- setHasRightPanelToggled(persistedIsRightPanelShown);+ setSelectedTab(persistedState.selectedTab);+ setHasRightPanelToggled(persistedState.rightPanelShown);}, [setSelectedTab,setHasRightPanelToggled,- persistedSelectedTab,- persistedIsRightPanelShown,+ persistedState.selectedTab,+ persistedState.rightPanelShown,]);useEffect(() => {@@ -89,13 +77,13 @@ export function ConversationTabs() {if (selectedTab === tab && isRightPanelShown) {// If clicking the same active tab, close the drawersetHasRightPanelToggled(false);- setPersistedIsRightPanelShown(false);+ setPersistedRightPanelShown(false);} else {// If clicking a different tab or drawer is closed, open drawer and select tabonTabChange(tab);if (!isRightPanelShown) {setHasRightPanelToggled(true);- setPersistedIsRightPanelShown(true);+ setPersistedRightPanelShown(true);}}};@@ -166,7 +154,7 @@ export function ConversationTabs() {// Filter out unpinned tabsconst visibleTabs = tabs.filter(- (tab) => !persistedUnpinnedTabs.includes(tab.tabValue),+ (tab) => !persistedState.unpinnedTabs.includes(tab.tabValue),);return (diff --git a/frontend/src/hooks/mutation/use-delete-conversation.ts b/frontend/src/hooks/mutation/use-delete-conversation.tsindex e654cd6d7e..b28d760e2e 100644--- a/frontend/src/hooks/mutation/use-delete-conversation.ts+++ b/frontend/src/hooks/mutation/use-delete-conversation.ts@@ -1,5 +1,6 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import ConversationService from "#/api/conversation-service/conversation-service.api";+import { clearConversationLocalStorage } from "#/utils/conversation-local-storage";export const useDeleteConversation = () => {const queryClient = useQueryClient();@@ -24,6 +25,11 @@ export const useDeleteConversation = () => {return { previousConversations };},++ onSuccess: (_, variables) => {+ clearConversationLocalStorage(variables.conversationId);+ },+onError: (err, variables, context) => {if (context?.previousConversations) {queryClient.setQueryData(diff --git a/frontend/src/utils/conversation-local-storage.ts b/frontend/src/utils/conversation-local-storage.tsnew file mode 100644index 0000000000..dcd77a2b4b--- /dev/null+++ b/frontend/src/utils/conversation-local-storage.ts@@ -0,0 +1,110 @@+import { useState } from "react";+import type { ConversationTab } from "#/stores/conversation-store";++export const LOCAL_STORAGE_KEYS = {+ CONVERSATION_STATE: "conversation-state",+} as const;++/**+ * Consolidated conversation state stored in a single localStorage key.+ */+export interface ConversationState {+ selectedTab: ConversationTab | null;+ rightPanelShown: boolean;+ unpinnedTabs: string[];+}++const DEFAULT_CONVERSATION_STATE: ConversationState = {+ selectedTab: "editor",+ rightPanelShown: true,+ unpinnedTabs: [],+};++/**+ * Check if a conversation ID is a temporary task ID that should not be persisted.+ * Task IDs have the format "task-{uuid}" and are used during V1 conversation initialization.+ */+export function isTaskConversationId(conversationId: string): boolean {+ return conversationId.startsWith("task-");+}++/**+ * Get the full conversation state from localStorage.+ */+export function getConversationState(+ conversationId: string,+): ConversationState {+ if (isTaskConversationId(conversationId)) {+ return DEFAULT_CONVERSATION_STATE;+ }+ try {+ const key = `${LOCAL_STORAGE_KEYS.CONVERSATION_STATE}-${conversationId}`;+ const item = localStorage.getItem(key);+ if (item !== null) {+ return { ...DEFAULT_CONVERSATION_STATE, ...JSON.parse(item) };+ }+ return DEFAULT_CONVERSATION_STATE;+ } catch {+ return DEFAULT_CONVERSATION_STATE;+ }+}++/**+ * Set the conversation state in localStorage, merging with existing state.+ */+export function setConversationState(+ conversationId: string,+ updates: Partial<ConversationState>,+): void {+ if (isTaskConversationId(conversationId)) {+ return;+ }+ try {+ const key = `${LOCAL_STORAGE_KEYS.CONVERSATION_STATE}-${conversationId}`;+ const currentState = getConversationState(conversationId);+ const newState = { ...currentState, ...updates };+ localStorage.setItem(key, JSON.stringify(newState));+ } catch (err) {+ console.warn("Failed to set conversation localStorage", err);+ }+}++export function clearConversationLocalStorage(conversationId: string) {+ try {+ const key = `${LOCAL_STORAGE_KEYS.CONVERSATION_STATE}-${conversationId}`;+ localStorage.removeItem(key);+ } catch (err) {+ console.warn(+ "Failed to clear conversation localStorage",+ conversationId,+ err,+ );+ }+}++/**+ * React hook for conversation-scoped localStorage state.+ * Returns the full state and individual setters for each property.+ */+export function useConversationLocalStorageState(conversationId: string): {+ state: ConversationState;+ setSelectedTab: (tab: ConversationTab | null) => void;+ setRightPanelShown: (shown: boolean) => void;+ setUnpinnedTabs: (tabs: string[]) => void;+} {+ const [state, setState] = useState<ConversationState>(() =>+ getConversationState(conversationId),+ );++ const updateState = (updates: Partial<ConversationState>) => {+ setState((prev) => ({ ...prev, ...updates }));+ setConversationState(conversationId, updates);+ };++ return {+ state,+ setSelectedTab: (tab) => updateState({ selectedTab: tab }),+ setRightPanelShown: (shown) => updateState({ rightPanelShown: shown }),+ setUnpinnedTabs: (tabs) => updateState({ unpinnedTabs: tabs }),+ };+}