Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(frontend): keep user messages when switching conversations (#923)

Hiep Lebc530f813d06
diff --git a/__tests__/contexts/conversation-websocket-context.test.tsx b/__tests__/contexts/conversation-websocket-context.test.tsx
new file mode 100644
index 0000000000..8cdacb4d4b
--- /dev/null
+++ b/__tests__/contexts/conversation-websocket-context.test.tsx
@@ -0,0 +1,123 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { render, waitFor, act } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { createUserMessageEvent } from "test-utils";
+import { ConversationWebSocketProvider } from "#/contexts/conversation-websocket-context";
+import { useEventStore } from "#/stores/use-event-store";
+import { useOptimisticUserMessageStore } from "#/stores/optimistic-user-message-store";
+import { useUserConversation } from "#/hooks/query/use-user-conversation";
+import EventService from "#/api/event-service/event-service.api";
+import type { MessageEvent } from "#/types/agent-server/core";
+
+// Keep the units under test real (the provider, `useConversationHistory`, the
+// event store). Only the network is stubbed: the WebSocket transport and the
+// REST service the history query depends on.
+vi.mock("#/hooks/use-websocket", () => ({
+ useWebSocket: vi.fn(() => ({ socket: null, reconnect: vi.fn() })),
+}));
+vi.mock("#/hooks/query/use-user-conversation", () => ({
+ useUserConversation: vi.fn(),
+}));
+
+const AGENT_REPLY_ID = "evt-agent-reply";
+
+// An agent reply that streamed in over the WebSocket *after* the initial REST
+// history page β€” i.e. it lives only in the event store, never in the cached
+// history page. This is the class of event the old code dropped on re-entry.
+const makeAgentReply = (): MessageEvent => ({
+ id: AGENT_REPLY_ID,
+ timestamp: new Date(Date.now() + 1000).toISOString(),
+ source: "agent",
+ llm_message: { role: "assistant", content: [{ type: "text", text: "Hi!" }] },
+ activated_microagents: [],
+ extended_content: [],
+});
+
+const eventIds = () => useEventStore.getState().events.map((event) => event.id);
+
+describe("ConversationWebSocketProvider β€” conversation-scoped event store", () => {
+ let queryClient: QueryClient;
+
+ const renderProvider = (conversationId: string) =>
+ render(
+ <QueryClientProvider client={queryClient}>
+ <ConversationWebSocketProvider
+ conversationId={conversationId}
+ conversationUrl={null}
+ >
+ <div />
+ </ConversationWebSocketProvider>
+ </QueryClientProvider>,
+ );
+
+ beforeEach(() => {
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ useEventStore.setState({
+ events: [],
+ eventIds: new Set(),
+ uiEvents: [],
+ loadedConversationId: null,
+ });
+ useOptimisticUserMessageStore.setState({ pendingMessages: [] });
+
+ vi.mocked(useUserConversation).mockReturnValue({
+ data: { conversation_url: "http://localhost/api", session_api_key: null },
+ } as ReturnType<typeof useUserConversation>);
+
+ // The cached REST history page ends at the user's message β€” a fresh page
+ // per conversation so we can detect cross-conversation leakage.
+ vi.spyOn(EventService, "searchEvents").mockImplementation(
+ async (conversationId: string) => ({
+ items: [createUserMessageEvent(`user-msg-${conversationId}`)],
+ next_page_id: null,
+ }),
+ );
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("clears the previous conversation's events when switching conversations", async () => {
+ // Arrange + Act: open conversation A.
+ const { rerender } = renderProvider("conv-a");
+ await waitFor(() => expect(eventIds()).toEqual(["user-msg-conv-a"]));
+
+ // Act: switch to conversation B.
+ rerender(
+ <QueryClientProvider client={queryClient}>
+ <ConversationWebSocketProvider conversationId="conv-b" conversationUrl={null}>
+ <div />
+ </ConversationWebSocketProvider>
+ </QueryClientProvider>,
+ );
+
+ // Assert: B's history replaced A's β€” A did not leak into B.
+ await waitFor(() => expect(eventIds()).toEqual(["user-msg-conv-b"]));
+ });
+
+ it("keeps events that arrived after history when re-entering the same conversation", async () => {
+ // Arrange: open conversation A, then receive an agent reply over the socket
+ // that is not part of the cached REST history page.
+ const { unmount } = renderProvider("conv-a");
+ await waitFor(() => expect(eventIds()).toEqual(["user-msg-conv-a"]));
+ act(() => {
+ useEventStore.getState().addEvent(makeAgentReply());
+ });
+
+ // Act: leave (e.g. to Settings) and return to the same conversation.
+ unmount();
+ renderProvider("conv-a");
+
+ // Assert: both the user message and the streamed reply survive re-entry.
+ await waitFor(() =>
+ expect(eventIds()).toEqual(["user-msg-conv-a", AGENT_REPLY_ID]),
+ );
+ // ...and the re-seed deduped against the existing user message rather than
+ // appending a second copy β€” exactly two events, no double-insertion.
+ expect(eventIds()).toHaveLength(2);
+ });
+});
diff --git a/src/contexts/conversation-websocket-context.tsx b/src/contexts/conversation-websocket-context.tsx
index e7ea2c0088..4d38cf9809 100644
--- a/src/contexts/conversation-websocket-context.tsx
+++ b/src/contexts/conversation-websocket-context.tsx
@@ -133,6 +133,9 @@ export function ConversationWebSocketProvider({
const queryClient = useQueryClient();
const addEvent = useEventStore((state) => state.addEvent);
const addEvents = useEventStore((state) => state.addEvents);
+ const clearEventsForConversation = useEventStore(
+ (state) => state.clearEventsForConversation,
+ );
const { setErrorMessage, removeErrorMessage, clearConnectionError } =
useErrorMessageStore();
const consumeMatchingPendingMessage = useOptimisticUserMessageStore(
@@ -219,6 +222,27 @@ export function ConversationWebSocketProvider({
const isLoadingHistoryMain = !!conversationId && isPreloadingHistory;
+ // Clear the (global, not conversation-scoped) event store when the active
+ // conversation changes, BEFORE the preloaded-history effect below re-seeds
+ // it. This MUST live here rather than in the route component: a parent's
+ // passive effect runs *after* this child's layout effects, so clearing from
+ // the route would wipe the freshly seeded history. On a conversation switch
+ // the history page is already cached, so `preloadedHistory` is available
+ // synchronously β€” without ordering the clear first, the user's already-echoed
+ // message gets seeded then immediately wiped, leaving only the `since`
+ // WebSocket resend (the agent's reply). Re-entering the same conversation is
+ // a no-op, so the store survives navigating away to Settings and back.
+ useLayoutEffect(() => {
+ const nextId = conversationId ?? null;
+ if (useEventStore.getState().loadedConversationId === nextId) {
+ return;
+ }
+ // Single atomic action: clears the previous conversation's events and
+ // records the new loaded id in one `set`, so no subscriber can observe a
+ // half-applied state (events gone but the old id still reported).
+ clearEventsForConversation(nextId);
+ }, [conversationId, clearEventsForConversation]);
+
useLayoutEffect(() => {
if (!preloadedHistory || preloadedHistory.events.length === 0) {
return;
diff --git a/src/routes/conversation.tsx b/src/routes/conversation.tsx
index e210ea8798..c22810997b 100644
--- a/src/routes/conversation.tsx
+++ b/src/routes/conversation.tsx
@@ -29,14 +29,12 @@ import {
import { WebSocketProviderWrapper } from "#/contexts/websocket-provider-wrapper";
import { useErrorMessageStore } from "#/stores/error-message-store";
import { I18nKey } from "#/i18n/declaration";
-import { useEventStore } from "#/stores/use-event-store";
import { resumeCloudSandbox } from "#/api/cloud/conversation-service.api";
function AppContent() {
const { t } = useTranslation("openhands");
const { conversationId } = useConversationId();
const panelViewMatch = useMatch("/conversations/:conversationId/panel");
- const clearEvents = useEventStore((state) => state.clearEvents);
const { isTask, taskStatus, taskDetail } = useTaskPolling();
@@ -70,13 +68,16 @@ function AppContent() {
(state) => state.removeErrorMessage,
);
+ // Per-conversation UI/runtime resets. The event store is cleared separately,
+ // inside ConversationWebSocketProvider, so the clear is ordered *before* the
+ // preloaded-history re-seed (see the note there) β€” clearing it here would run
+ // too late and wipe the freshly seeded history on a conversation switch.
React.useEffect(() => {
clearTerminal();
resetConversationState();
resetConversationRuntimeState();
setCurrentAgentState(AgentState.LOADING);
removeErrorMessage();
- clearEvents();
}, [
conversationId,
clearTerminal,
@@ -84,7 +85,6 @@ function AppContent() {
resetConversationRuntimeState,
setCurrentAgentState,
removeErrorMessage,
- clearEvents,
]);
React.useEffect(() => {
diff --git a/src/stores/use-event-store.ts b/src/stores/use-event-store.ts
index 6abd6c81d5..3766f4af79 100644
--- a/src/stores/use-event-store.ts
+++ b/src/stores/use-event-store.ts
@@ -51,6 +51,14 @@ export interface EventState {
events: OHEvent[];
eventIds: Set<string | number>;
uiEvents: OHEvent[];
+ /**
+ * The conversation whose events currently populate the store. The store is
+ * global (not keyed by conversation), so the conversation route uses this to
+ * tell a genuine conversation switch apart from a remount of the *same*
+ * conversation (e.g. navigating to Settings and back) β€” only the former
+ * should clear the accumulated events.
+ */
+ loadedConversationId: string | null;
addEvent: (event: OHEvent) => void;
/**
* Bulk-insert events. Used for the initial REST history load and for
@@ -59,7 +67,21 @@ export interface EventState {
* timestamp so older pages drop into the correct position.
*/
addEvents: (events: OHEvent[]) => void;
+ /**
+ * Clear all events. Also resets `loadedConversationId` to `null` so the
+ * store never claims to hold a conversation whose events have been wiped β€”
+ * the invariant (`loadedConversationId` reflects the conversation whose
+ * events are in the arrays) holds even for a standalone clear.
+ */
clearEvents: () => void;
+ /**
+ * Atomically clear all events and record which conversation is now loaded.
+ * Collapsing the reset and the bookkeeping into a single `set` keeps the
+ * store invariant enforced at the boundary, rather than relying on every
+ * call-site to invoke a clear and a `loadedConversationId` setter in the
+ * right order.
+ */
+ clearEventsForConversation: (conversationId: string | null) => void;
}
const appendEvent = (state: EventState, event: OHEvent): EventState => {
@@ -108,6 +130,7 @@ export const useEventStore = create<EventState>()((set) => ({
events: [],
eventIds: new Set(),
uiEvents: [],
+ loadedConversationId: null,
addEvent: (event: OHEvent) => set((state) => applyAddEvent(state, event)),
addEvents: (incoming: OHEvent[]) =>
set((state) => {
@@ -148,6 +171,14 @@ export const useEventStore = create<EventState>()((set) => ({
events: [],
eventIds: new Set(),
uiEvents: [],
+ loadedConversationId: null,
+ })),
+ clearEventsForConversation: (conversationId: string | null) =>
+ set(() => ({
+ events: [],
+ eventIds: new Set(),
+ uiEvents: [],
+ loadedConversationId: conversationId,
})),
}));