π OpenHands: AI-Driven Development
fix(frontend): deduplicate events on WebSocket reconnect (#12197)
sp.wack1480d4acb03b
diff --git a/frontend/__tests__/conversation-websocket-handler.test.tsx b/frontend/__tests__/conversation-websocket-handler.test.tsxindex eb9c8976ff..ab6243e100 100644--- a/frontend/__tests__/conversation-websocket-handler.test.tsx+++ b/frontend/__tests__/conversation-websocket-handler.test.tsx@@ -35,6 +35,7 @@ import {} from "#/contexts/conversation-websocket-context";import { conversationWebSocketTestSetup } from "./helpers/msw-websocket-setup";import { useEventStore } from "#/stores/use-event-store";+import { isV1Event } from "#/types/v1/type-guards";// MSW WebSocket mock setupconst { wsLink, server: mswServer } = conversationWebSocketTestSetup();@@ -424,6 +425,101 @@ describe("Conversation WebSocket Handler", () => {// based on how the actual reconnection logic is implemented});+ it("should not create duplicate events when WebSocket reconnects with resend_all=true", async () => {+ const conversationId = "test-conversation-reconnect";+ let connectionCount = 0;++ // Clear event store before test+ useEventStore.getState().clearEvents();++ // Create mock events that will be sent on each connection+ const mockHistoryEvents = [+ createMockUserMessageEvent({ id: "event-1" }),+ createMockMessageEvent({ id: "event-2" }),+ createMockMessageEvent({ id: "event-3" }),+ ];++ // Set up MSW to mock event count API and WebSocket+ // The WebSocket will resend all events on each connection (simulating resend_all=true behavior)+ mswServer.use(+ http.get(+ `http://localhost:3000/api/conversations/${conversationId}/events/count`,+ () => HttpResponse.json(3),+ ),+ wsLink.addEventListener("connection", ({ client, server }) => {+ connectionCount += 1;+ server.connect();++ // Send all history events on EVERY connection (simulating resend_all=true)+ mockHistoryEvents.forEach((event) => {+ client.send(JSON.stringify(event));+ });++ // On first connection, simulate a disconnect after events are sent+ if (connectionCount === 1) {+ setTimeout(() => {+ client.close(1006, "Simulated disconnect");+ }, 100);+ }+ }),+ );++ // Render with WebSocket context+ renderWithWebSocketContext(+ <ConnectionStatusComponent />,+ conversationId,+ `http://localhost:3000/api/conversations/${conversationId}`,+ );++ // Wait for initial connection and events+ await waitFor(() => {+ expect(screen.getByTestId("connection-state")).toHaveTextContent(+ "OPEN",+ );+ });++ await waitFor(() => {+ expect(useEventStore.getState().events.length).toBe(3);+ });++ // Wait for disconnect+ await waitFor(() => {+ expect(screen.getByTestId("connection-state")).toHaveTextContent(+ "CLOSED",+ );+ });++ // Wait for reconnection+ await waitFor(+ () => {+ expect(screen.getByTestId("connection-state")).toHaveTextContent(+ "OPEN",+ );+ },+ { timeout: 5000 },+ );++ // Give time for resent events to be processed+ await new Promise((resolve) => {+ setTimeout(resolve, 200);+ });++ // After reconnection, events should NOT be duplicated+ // The server sends 3 events again (resend_all=true), but we should deduplicate+ const { events } = useEventStore.getState();+ const v1Events = events.filter(isV1Event);+ const uniqueEventIds = [...new Set(v1Events.map((e) => e.id))];++ // This assertion will FAIL with current implementation (showing the bug)+ // Expected: 3 events (deduplicated)+ // Actual: 6 events (duplicated)+ expect(v1Events.length).toBe(3);+ expect(uniqueEventIds.length).toBe(3);++ // Verify we actually had 2 connections+ expect(connectionCount).toBe(2);+ });+it.todo("should track and display errors with proper metadata");it.todo("should set appropriate error states on connection failures");it.todo(diff --git a/frontend/src/stores/use-event-store.ts b/frontend/src/stores/use-event-store.tsindex 2d8ecf0a3b..b4653ee318 100644--- a/frontend/src/stores/use-event-store.ts+++ b/frontend/src/stores/use-event-store.ts@@ -9,8 +9,12 @@ type OHEvent = (OpenHandsEvent | OpenHandsParsedEvent) & {isFromPlanningAgent?: boolean;};+const getEventId = (event: OHEvent): string | number | undefined =>+ "id" in event ? event.id : undefined;+interface EventState {events: OHEvent[];+ eventIds: Set<string | number>;uiEvents: OHEvent[];addEvent: (event: OHEvent) => void;clearEvents: () => void;@@ -18,10 +22,21 @@ interface EventState {export const useEventStore = create<EventState>()((set) => ({events: [],+ eventIds: new Set(),uiEvents: [],addEvent: (event: OHEvent) =>set((state) => {+ // Deduplicate: skip if event with same id already exists (O(1) lookup)+ const eventId = getEventId(event);+ if (eventId !== undefined && state.eventIds.has(eventId)) {+ return state;+ }+const newEvents = [...state.events, event];+ const newEventIds =+ eventId !== undefined+ ? new Set(state.eventIds).add(eventId)+ : state.eventIds;const newUiEvents = isV1Event(event)? // @ts-expect-error - temporary, needs proper typinghandleEventForUI(event, state.uiEvents)@@ -29,12 +44,14 @@ export const useEventStore = create<EventState>()((set) => ({return {events: newEvents,+ eventIds: newEventIds,uiEvents: newUiEvents,};}),clearEvents: () =>set(() => ({events: [],+ eventIds: new Set(),uiEvents: [],})),}));