π OpenHands: AI-Driven Development
fix: stop tripping SaaS 500 on cloud conversation history (#360)
Hiep Le6bb94b8bf0c7
diff --git a/__tests__/api/event-service.test.ts b/__tests__/api/event-service.test.tsnew file mode 100644index 0000000000..e92009579e--- /dev/null+++ b/__tests__/api/event-service.test.ts@@ -0,0 +1,60 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import EventService from "#/api/event-service/event-service.api";+import { callCloudProxy } from "#/api/cloud/proxy";+import type { Backend } from "#/api/backend-registry/types";++vi.mock("#/api/cloud/proxy", () => ({+ callCloudProxy: vi.fn(),+}));++const cloudBackend: Backend = {+ id: "cloud-1",+ name: "Production",+ host: "https://app.all-hands.dev",+ apiKey: "cloud-key",+ kind: "cloud",+};++beforeEach(() => {+ window.localStorage.clear();+ __resetActiveStoreForTests();+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-1" });+ vi.mocked(callCloudProxy).mockReset();+ vi.mocked(callCloudProxy).mockResolvedValue({ items: [], next_page_id: null });+});++afterEach(() => {+ window.localStorage.clear();+ __resetActiveStoreForTests();+ vi.mocked(callCloudProxy).mockReset();+});++describe("EventService.searchEvents β cloud branch", () => {+ it("strips timestamp/sort/page params and clamps limit to <=100", async () => {+ // Arrange: the caller (e.g. `useLoadOlderEvents`) may pass pagination+ // filters the OpenHands SaaS App API can't handle without 500-ing.+ // The cloud branch must mirror the cloud frontend's shape: limit only.+ const options = {+ limit: 500,+ sortOrder: "TIMESTAMP_DESC" as const,+ pageId: "p1",+ timestampGte: "2026-05-01T00:00:00.000000",+ timestampLt: "2026-05-12T07:20:29.087853",+ };++ // Act+ await EventService.searchEvents("conv-1", null, null, options);++ // Assert: forwarded path contains only limit=100 (caller's 500 clamped).+ const proxyCall = vi.mocked(callCloudProxy).mock.calls[0][0];+ expect(proxyCall.path).toBe(+ "/api/v1/conversation/conv-1/events/search?limit=100",+ );+ });+});diff --git a/__tests__/hooks/use-load-older-events.test.tsx b/__tests__/hooks/use-load-older-events.test.tsxindex 953b132d1f..31a58a9f5d 100644--- a/__tests__/hooks/use-load-older-events.test.tsx+++ b/__tests__/hooks/use-load-older-events.test.tsx@@ -15,6 +15,11 @@ import type { EventSearchPage } from "#/api/event-service/event-service.types";vi.mock("#/api/event-service/event-service.api");vi.mock("#/hooks/query/use-user-conversation");+const mockUseActiveBackend = vi.fn();+vi.mock("#/contexts/active-backend-context", () => ({+ useActiveBackend: () => mockUseActiveBackend(),+}));+function makeConversation(): Conversation {// Cast: `useUserConversation` actually returns an `AppConversation` whose// event-host URL lives on `conversation_url` (not the `Conversation.url`@@ -72,6 +77,13 @@ describe("useLoadOlderEvents", () => {useEventStore.getState().clearEvents();});+ // Default to a local backend so existing tests exercise the+ // pagination path. Individual tests can override to cloud.+ mockUseActiveBackend.mockReturnValue({+ backend: { kind: "local" },+ orgId: null,+ });+vi.mocked(useUserConversation).mockReturnValue({data: makeConversation(),isLoading: false,@@ -287,6 +299,35 @@ describe("useLoadOlderEvents", () => {+ it("disables REST older-event pagination for cloud backends", async () => {+ // Arrange: cloud backend active, plus an anchor event in the store+ // that would otherwise let `loadOlder` issue a `timestamp__lt` request.+ mockUseActiveBackend.mockReturnValue({+ backend: { kind: "cloud" },+ orgId: "org-1",+ });+ act(() => {+ useEventStore+ .getState()+ .addEvent(makeEvent("evt-recent", "2024-06-01T00:00:00Z"));+ });+ const spy = vi.spyOn(EventService, "searchEvents");++ const { result } = renderHook(() => useLoadOlderEvents("conv-1"), {+ wrapper,+ });++ // Act+ await act(async () => {+ await result.current.loadOlder();+ });++ // Assert: cloud short-circuits β no request fires and hasMore is false+ // from first render so the chat scroll handler never triggers.+ expect(spy).not.toHaveBeenCalled();+ expect(result.current.hasMore).toBe(false);+ });+it("stops paginating and throws when the oldest loaded event is missing a timestamp", async () => {act(() => {useEventStorediff --git a/src/api/event-service/event-service.api.ts b/src/api/event-service/event-service.api.tsindex 9cc94bb787..f2a1f294cc 100644--- a/src/api/event-service/event-service.api.ts+++ b/src/api/event-service/event-service.api.ts@@ -104,13 +104,21 @@ class EventService {if (active.kind === "cloud") {// Event *history* lives on the SaaS App API, not the runtime// sandbox. Path is singular `conversation` and v1-prefixed.+ //+ // Mirror the OpenHands SaaS frontend's request shape and send ONLY+ // `limit`. The SaaS app-server's `search_events` has a server-side+ // TypeError when filtering by `timestamp__lt` / `timestamp__gte`+ // (it compares the stored `event.timestamp` str against the parsed+ // datetime, which raises in Python 3 and surfaces as HTTP 500). The+ // cloud frontend has never sent timestamp/sort/page filters here,+ // so the broken path is untested; the safe contract is "limit+ // only" until the server is fixed. `sort_order` and `page_id` are+ // also dropped β neither is part of the proven-working shape, and+ // older-event pagination is gated off in `useLoadOlderEvents` for+ // cloud, so they have no caller to satisfy.+ const cloudLimit = Math.min(limit, 100);const params = new URLSearchParams();- params.set("limit", String(limit));- if (options.pageId) params.set("page_id", options.pageId);- if (options.sortOrder) params.set("sort_order", options.sortOrder);- if (options.timestampGte)- params.set("timestamp__gte", options.timestampGte);- if (options.timestampLt) params.set("timestamp__lt", options.timestampLt);+ params.set("limit", String(cloudLimit));const data = await callCloudProxy<EventSearchPage<OpenHandsEvent>>({backend: active,diff --git a/src/hooks/use-load-older-events.ts b/src/hooks/use-load-older-events.tsindex d13251f082..6a1787513f 100644--- a/src/hooks/use-load-older-events.ts+++ b/src/hooks/use-load-older-events.ts@@ -3,6 +3,7 @@ import EventService from "#/api/event-service/event-service.api";import { useUserConversation } from "#/hooks/query/use-user-conversation";import { useEventStore } from "#/stores/use-event-store";import { INITIAL_HISTORY_PAGE_SIZE } from "#/hooks/query/use-conversation-history";+import { useActiveBackend } from "#/contexts/active-backend-context";import type { OpenHandsEvent } from "#/types/agent-server/core";const getEventTimestamp = (event: OpenHandsEvent): string | undefined =>@@ -25,27 +26,40 @@ interface UseLoadOlderEventsResult {* REST-side companion to `useConversationHistory`: paginates older events* (`timestamp < oldest known`) into the event store on demand. Used by the* chat scroll handler to lazily backfill history when the user scrolls up.+ *+ * Cloud-mode caveat: REST-side older-event pagination is **disabled** for+ * cloud backends. The SaaS app-server's `search_events` 500s when called+ * with `timestamp__lt` / `timestamp__gte` (compares stored event.timestamp+ * `str` against the parsed `datetime` and raises `TypeError`). Until the+ * server-side bug at `openhands/app_server/event/event_service_base.py`+ * (lines ~101β103) is fixed, the hook reports `hasMore: false` from first+ * render and `loadOlder` is a no-op for cloud β matching the OpenHands+ * cloud frontend, which never paginates older events either.*/export const useLoadOlderEvents = (conversationId?: string | null,): UseLoadOlderEventsResult => {const { data: conversation } = useUserConversation(conversationId ?? null);const addEvents = useEventStore((state) => state.addEvents);+ const isCloud = useActiveBackend().backend.kind === "cloud";const [isLoading, setIsLoading] = React.useState(false);- const [hasMore, setHasMore] = React.useState(true);+ const [hasMore, setHasMore] = React.useState(!isCloud);const isLoadingRef = React.useRef(false);- const hasMoreRef = React.useRef(true);+ const hasMoreRef = React.useRef(!isCloud);- // Reset the pagination cursor whenever we switch conversations.+ // Reset the pagination cursor whenever we switch conversations or+ // backends. Cloud backends never have more older events to fetch via+ // REST (see top-of-file comment), so `hasMore` settles to `false`.React.useEffect(() => {- hasMoreRef.current = true;+ hasMoreRef.current = !isCloud;isLoadingRef.current = false;- setHasMore(true);+ setHasMore(!isCloud);setIsLoading(false);- }, [conversationId]);+ }, [conversationId, isCloud]);const loadOlder = React.useCallback(async () => {+ if (isCloud) return;if (!conversationId || isLoadingRef.current || !hasMoreRef.current) {return;}@@ -108,6 +122,7 @@ export const useLoadOlderEvents = (conversation?.conversation_url,conversation?.session_api_key,addEvents,+ isCloud,]);return { isLoading, hasMore, loadOlder };