Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: preload conversation history before websocket connection (#12488)

Mohammed Abdulaia87b4efd4111
diff --git a/frontend/__tests__/hooks/query/use-conversation-history.test.tsx b/frontend/__tests__/hooks/query/use-conversation-history.test.tsx
new file mode 100644
index 0000000000..50048aeda7
--- /dev/null
+++ b/frontend/__tests__/hooks/query/use-conversation-history.test.tsx
@@ -0,0 +1,116 @@
+// @vitest-environment happy-dom
+
+import { describe, it, expect, afterEach, vi } from "vitest";
+import React from "react";
+import { renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+
+import { useConversationHistory } from "#/hooks/query/use-conversation-history";
+import EventService from "#/api/event-service/event-service.api";
+import { useUserConversation } from "#/hooks/query/use-user-conversation";
+import type { Conversation } from "#/api/open-hands.types";
+import type { OpenHandsEvent } from "#/types/v1/core";
+
+function makeConversation(version: "V0" | "V1"): Conversation {
+ return {
+ conversation_id: "conv-test",
+ title: "Test Conversation",
+ selected_repository: null,
+ selected_branch: null,
+ git_provider: null,
+ last_updated_at: new Date().toISOString(),
+ created_at: new Date().toISOString(),
+ status: "RUNNING",
+ runtime_status: null,
+ url: null,
+ session_api_key: null,
+ conversation_version: version,
+ };
+}
+
+function makeEvent(): OpenHandsEvent {
+ return {
+ id: "evt-1",
+ } as OpenHandsEvent;
+}
+
+// --------------------
+// Mocks
+// --------------------
+vi.mock("#/api/open-hands-axios", () => ({
+ openHands: {
+ get: vi.fn(),
+ },
+}));
+
+vi.mock("#/api/event-service/event-service.api");
+vi.mock("#/hooks/query/use-user-conversation");
+
+const queryClient = new QueryClient();
+
+function wrapper({ children }: { children: React.ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+}
+
+// --------------------
+// Tests
+// --------------------
+describe("useConversationHistory", () => {
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("calls V1 REST endpoint for V1 conversations", async () => {
+ const v1SearchEventsSpy = vi.spyOn(EventService, "searchEventsV1");
+
+ vi.mocked(useUserConversation).mockReturnValue({
+ data: makeConversation("V1"),
+ isLoading: false,
+ isPending: false,
+ isError: false,
+ error: null,
+ refetch: vi.fn(),
+ } as any);
+
+ v1SearchEventsSpy.mockResolvedValue([makeEvent()]);
+
+ const { result } = renderHook(() => useConversationHistory("conv-123"), {
+ wrapper,
+ });
+
+ await waitFor(() => {
+ expect(result.current.data).toBeDefined();
+ });
+
+ expect(EventService.searchEventsV1).toHaveBeenCalledWith("conv-123");
+ expect(EventService.searchEventsV0).not.toHaveBeenCalled();
+ });
+
+ it("calls V0 REST endpoint for V0 conversations", async () => {
+ const v0SearchEventsSpy = vi.spyOn(EventService, "searchEventsV0");
+
+ vi.mocked(useUserConversation).mockReturnValue({
+ data: makeConversation("V0"),
+ isLoading: false,
+ isPending: false,
+ isError: false,
+ error: null,
+ refetch: vi.fn(),
+ } as any);
+
+ v0SearchEventsSpy.mockResolvedValue([makeEvent()]);
+
+ const { result } = renderHook(() => useConversationHistory("conv-456"), {
+ wrapper,
+ });
+
+ await waitFor(() => {
+ expect(result.current.data).toBeDefined();
+ });
+
+ expect(EventService.searchEventsV0).toHaveBeenCalledWith("conv-456");
+ expect(EventService.searchEventsV1).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/api/event-service/event-service.api.ts b/frontend/src/api/event-service/event-service.api.ts
index 7464480d5c..0d19595841 100644
--- a/frontend/src/api/event-service/event-service.api.ts
+++ b/frontend/src/api/event-service/event-service.api.ts
@@ -5,6 +5,8 @@ import type {
ConfirmationResponseRequest,
ConfirmationResponseResponse,
} from "./event-service.types";
+import { openHands } from "../open-hands-axios";
+import { OpenHandsEvent } from "#/types/v1/core";
class EventService {
/**
@@ -61,5 +63,27 @@ class EventService {
);
return data;
}
+
+ // V1 conversations β€” App Server REST endpoint
+ static async searchEventsV1(conversationId: string, limit = 100) {
+ const { data } = await openHands.get<{
+ items: OpenHandsEvent[];
+ }>(`/api/v1/conversation/${conversationId}/events/search`, {
+ params: { limit },
+ });
+
+ return data.items;
+ }
+
+ // V0 conversations β€” Legacy REST endpoint
+ static async searchEventsV0(conversationId: string, limit = 100) {
+ const { data } = await openHands.get<{
+ events: OpenHandsEvent[];
+ }>(`/api/conversations/${conversationId}/events`, {
+ params: { limit },
+ });
+
+ return data.events;
+ }
}
export default EventService;
diff --git a/frontend/src/contexts/conversation-websocket-context.tsx b/frontend/src/contexts/conversation-websocket-context.tsx
index 7f68b00abc..3fd59a6985 100644
--- a/frontend/src/contexts/conversation-websocket-context.tsx
+++ b/frontend/src/contexts/conversation-websocket-context.tsx
@@ -46,6 +46,7 @@ import { useTracking } from "#/hooks/use-tracking";
import { useReadConversationFile } from "#/hooks/mutation/use-read-conversation-file";
import useMetricsStore from "#/stores/metrics-store";
import { I18nKey } from "#/i18n/declaration";
+import { useConversationHistory } from "#/hooks/query/use-conversation-history";
// eslint-disable-next-line @typescript-eslint/naming-convention
export type V1_WebSocketConnectionState =
@@ -306,6 +307,21 @@ export function ConversationWebSocketProvider({
latestPlanningFileEventRef.current = null;
}, [conversationId]);
+ const { data: preloadedEvents } = useConversationHistory(conversationId);
+
+ useEffect(() => {
+ if (!preloadedEvents || preloadedEvents.length === 0) {
+ setIsLoadingHistoryMain(false);
+ return;
+ }
+
+ for (const event of preloadedEvents) {
+ addEvent(event);
+ }
+
+ setIsLoadingHistoryMain(false);
+ }, [preloadedEvents, addEvent]);
+
// Separate message handlers for each connection
const handleMainMessage = useCallback(
(messageEvent: MessageEvent) => {
diff --git a/frontend/src/hooks/query/use-conversation-history.ts b/frontend/src/hooks/query/use-conversation-history.ts
new file mode 100644
index 0000000000..7fb4264602
--- /dev/null
+++ b/frontend/src/hooks/query/use-conversation-history.ts
@@ -0,0 +1,22 @@
+import { useQuery } from "@tanstack/react-query";
+import EventService from "#/api/event-service/event-service.api";
+import { useUserConversation } from "#/hooks/query/use-user-conversation";
+
+export const useConversationHistory = (conversationId?: string) => {
+ const { data: conversation } = useUserConversation(conversationId ?? null);
+
+ return useQuery({
+ queryKey: ["conversation-history", conversationId, conversation],
+ enabled: !!conversationId && !!conversation,
+ queryFn: async () => {
+ if (!conversationId || !conversation) return [];
+
+ if (conversation.conversation_version === "V1") {
+ return EventService.searchEventsV1(conversationId);
+ }
+
+ return EventService.searchEventsV0(conversationId);
+ },
+ staleTime: 30_000,
+ });
+};