Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Lazily load conversation history: 50 most recent first, paginate on s… (#252)

Robert Brennan491a3f6cdf26
diff --git a/AGENTS.md b/AGENTS.md
index c1e693ab97..73a291715f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -51,6 +51,10 @@
- No frontend version guard: `OptionService.getConfig()` calls `loadAgentServerInfo()` which fetches `/server_info` only to (a) detect an unreachable agent server (renders the onboarding screen via `AgentServerUnavailableError`) and (b) cache `usable_tools` for tool gating. All advertised versions are accepted. The "manage backends" modal displays each local backend's `/server_info.version` in light text via the `BACKEND$VERSION_LABEL` translation key.
- Backend registry: there is no longer a separate "bundled" backend. On first read of the `openhands-backends` localStorage key (`raw === null`), `readStoredBackends()` seeds the registry with one default local backend (`makeDefaultLocalBackend()`, id `BUNDLED_BACKEND_ID = "default-local"`, host/api-key from `agent-server-config`). After that the seed is just an ordinary registered backend β€” users can rename or remove it like any other. `getEffectiveLocalBackend()` returns the first registered local, falling back to a synthesized default if the registry has no locals (used by API clients that need a baseline `local` target). The "Manage backends" modal and the BackendSelector dropdown both read from the single registered list, so the seeded default appears in both without any special-casing.
- Shared `Dropdown` open behavior: when the menu opens, it clears the input/search text so callers can show the current selection via `placeholder` while still rendering the full option list. Generic dropdown tests should not expect the selected label to remain in the input after reopening unless the parent explicitly controls that display.
+- `useLoadOlderEvents` needs ref-based `isLoading` / `hasMore` guards in addition to React state because `ChatInterface` can trigger pagination from `onScroll`, `onWheel`, and the no-overflow effect in the same tick; closure-based state alone allows duplicate page requests.
+- `ChatInterface` continuity tests should assert that conversation messages render without the full `chat-messages-skeleton`, not that `data-testid="loading-spinner"` is absent: the lazy older-events indicator reuses the shared `LoadingSpinner` component and legitimately renders that inner test id while history backfill is running.
+- `useConversationHistory` now mirrors the older-events pagination fallback when the first page is exactly `INITIAL_HISTORY_PAGE_SIZE`: treat `next_page_id` **or** a full page as `hasMore`, so older agent-server variants that omit `next_page_id` still allow one more backfill request. The hook and `useLoadOlderEvents` also defensively reject mocked/malformed `page.items` responses before reversing them.
+
- `/server_info` tool capability metadata from `software-agent-sdk` PR #3028 ended up shipping as `usable_tools` (not `available_tools`). Frontend browser-tool gating should key off `usable_tools`, and still default to allowing tools when the server does not advertise tool metadata.
@@ -144,6 +148,15 @@
- Theme/customization tokens for the embedded shell are exposed as `--oh-*` CSS variables. Override them through `styleOverrides`, `style`, or host CSS targeting `[data-agent-server-ui]`; Tailwind theme tokens in `src/tailwind.css` should continue to reference those variables with `@theme inline` so host apps can restyle the UI without reworking component class names.
- Regression coverage for the CSS isolation work lives in `__tests__/agent-server-ui-providers.test.tsx`, `__tests__/agent-server-ui-style-scope.test.ts`, and the browser-level `tests/css-isolation.spec.ts` Playwright test.
+- Conversation history is loaded lazily, REST-first then WebSocket:
+ - `useConversationHistory` (in `src/hooks/query/use-conversation-history.ts`) fetches only the most recent `INITIAL_HISTORY_PAGE_SIZE` (default 50) events using `sort_order='TIMESTAMP_DESC'`, then reverses to chronological order. Older pages are paginated in via `useLoadOlderEvents` when the user scrolls near the top of the chat.
+ - `EventService.searchEvents(conversationId, conversationUrl, sessionApiKey, options)` returns the raw `EventSearchPage` (`{ items, next_page_id }`); options support `limit`, `pageId`, `sortOrder`, `timestampGte`, `timestampLt`. Both the local and cloud-proxy code paths forward the new params.
+ - The main `ConversationWebSocketProvider` waits for the REST query to settle before opening its socket, then connects with `resend_mode='since'` and `after_timestamp=<latest preloaded event ts>` (falling back to `'all'` when the REST result is empty or errored). The legacy `resend_all=true` flag is removed for the main connection; the planning-agent sub-conversation still uses `resend_all` until it is migrated to the same REST-then-WS pattern.
+ - The event store gained a bulk `addEvents(events)` action (used for the initial REST seed and for "scroll-up" pagination) that re-sorts by timestamp once at the end so older pages can be merged in cheaply. Per-event dedup still works via the existing `eventIds` set.
+ - `ChatInterface` wires `useLoadOlderEvents` into its scroll handler (threshold 80px from the top), shows a `data-testid="loading-older-events"` spinner during pagination, and preserves the visible scroll offset by storing the previous `scrollHeight` and adding the height delta after the older page renders.
+
+ - `useLoadOlderEvents` intentionally distinguishes between "no anchor yet" (empty store before the initial REST seed, so `loadOlder()` should no-op) and "malformed oldest event" (store has an oldest event with no timestamp, so the hook throws, flips `hasMore` false, and `ChatInterface` surfaces the failure via the shared error banner instead of failing silently).
+
- Action grouping in the chat stream:
- `src/components/conversation-events/chat/group-events.ts` folds runs of consecutive groupable events (regular `ActionEvent`/`ObservationEvent` cards, but not `FinishAction`, `ThinkAction`, `PlanningFileEditorObservation`, `TaskTrackerObservation`, hooks, errors, or message events) into single `RenderedItem` groups. The threshold lives in `EVENT_GROUP_MIN_SIZE` (currently 2, so even pairs of back-to-back actions get folded).
- `EventGroup` (`src/components/conversation-events/chat/event-message-components/event-group.tsx`) is the collapsible header that wraps each run. Default state is collapsed; the header shows `EVENT_GROUP$ACTIONS_COMPLETED` (with a success check) when the group is done, or `EVENT_GROUP$ACTIONS_PROGRESS` plus the currently-running action's title (from `getEventContent`) while a member `ActionEvent` has not yet been replaced by its observation in the UI events array. Expanding renders the original `EventMessage`s verbatim so each card still expands the way it did before.
diff --git a/__tests__/components/chat/chat-interface.test.tsx b/__tests__/components/chat/chat-interface.test.tsx
index d8a3e90e9b..070e3ef506 100644
--- a/__tests__/components/chat/chat-interface.test.tsx
+++ b/__tests__/components/chat/chat-interface.test.tsx
@@ -1,13 +1,5 @@
-import {
- afterEach,
- beforeEach,
- describe,
- expect,
- it,
- test,
- vi,
-} from "vitest";
-import { render, screen, within } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, test, vi } from "vitest";
+import { fireEvent, render, screen, within } from "@testing-library/react";
import { MemoryRouter, Route, Routes } from "react-router";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderWithProviders, useParamsMock } from "test-utils";
@@ -25,6 +17,7 @@ import { useUnifiedUploadFiles } from "#/hooks/mutation/use-unified-upload-files
import type { MessageEvent } from "#/types/agent-server/core";
import { useEventStore } from "#/stores/use-event-store";
import { useAgentState } from "#/hooks/use-agent-state";
+import { useLoadOlderEvents } from "#/hooks/use-load-older-events";
import { AgentState } from "#/types/agent-state";
vi.mock("#/hooks/query/use-config");
@@ -52,6 +45,10 @@ vi.mock("#/hooks/use-conversation-name-context-menu", () => ({
}),
}));
+vi.mock("#/hooks/use-load-older-events", () => ({
+ useLoadOlderEvents: vi.fn(),
+}));
+
vi.mock("#/hooks/use-agent-state", () => ({
useAgentState: vi.fn(() => ({
curAgentState: AgentState.AWAITING_USER_INPUT,
@@ -91,6 +88,14 @@ beforeEach(() => {
vi.mocked(useOptionalConversationId).mockReturnValue({
conversationId: "test-conversation-id",
});
+ // Default: pagination disabled (hasMore=false) so unrelated tests don't
+ // accidentally trigger loadOlder via the on-mount auto-trigger effect.
+ // Tests that exercise pagination override this.
+ vi.mocked(useLoadOlderEvents).mockReturnValue({
+ isLoading: false,
+ hasMore: false,
+ loadOlder: vi.fn().mockResolvedValue(undefined),
+ });
});
describe("ChatInterface - Chat Suggestions", () => {
@@ -187,10 +192,309 @@ describe("ChatInterface - Empty state", () => {
expect(repoSuggestions).toContain(suggestion.textContent);
});
});
+});
+
+describe("ChatInterface - Scroll-up loads older events", () => {
+ let queryClient: QueryClient;
+
+ beforeEach(() => {
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ useOptimisticUserMessageStore.setState({ optimisticUserMessage: null });
+ useErrorMessageStore.setState({ errorMessage: null });
+
+ (useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
+ data: {},
+ });
+ (useGetTrajectory as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
+ mutate: vi.fn(),
+ mutateAsync: vi.fn(),
+ isLoading: false,
+ });
+ (
+ useUnifiedUploadFiles as unknown as ReturnType<typeof vi.fn>
+ ).mockReturnValue({
+ mutateAsync: vi.fn(),
+ isLoading: false,
+ });
+ });
+
+ afterEach(() => {
+ useEventStore.setState({
+ events: [],
+ eventIds: new Set(),
+ uiEvents: [],
+ });
+ vi.clearAllMocks();
+ });
+
+ // Helper: install a controllable mock of useLoadOlderEvents and seed the
+ // store with one renderable user message so the chat mounts a scroll area.
+ const setupPaginationTest = () => {
+ const loadOlder = vi.fn().mockResolvedValue(undefined);
+ vi.mocked(useLoadOlderEvents).mockReturnValue({
+ isLoading: false,
+ hasMore: true,
+ loadOlder,
+ });
+ const seedEvent: MessageEvent = {
+ id: "msg-seed",
+ timestamp: "2025-07-01T00:00:00Z",
+ source: "user",
+ llm_message: {
+ role: "user",
+ content: [{ type: "text", text: "Existing message" }],
+ },
+ activated_microagents: [],
+ extended_content: [],
+ };
+ useEventStore.setState({
+ events: [seedEvent],
+ eventIds: new Set(["msg-seed"]),
+ uiEvents: [seedEvent],
+ });
+ return loadOlder;
+ };
+
+ // The auto-scroll-to-bottom hook schedules a rAF that does
+ // `dom.scrollTop = dom.scrollHeight`, which clobbers any value we set
+ // here before the test's event fires. Pin `scrollTop` as a stable
+ // getter so those assignments are no-ops.
+ const setScrollMetrics = (
+ el: HTMLElement,
+ metrics: { scrollTop: number; scrollHeight: number; clientHeight: number },
+ ) => {
+ Object.defineProperty(el, "scrollTop", {
+ configurable: true,
+ get: () => metrics.scrollTop,
+ set: () => {
+ /* swallow assignments from auto-scroll-to-bottom */
+ },
+ });
+ Object.defineProperty(el, "scrollHeight", {
+ configurable: true,
+ writable: true,
+ value: metrics.scrollHeight,
+ });
+ Object.defineProperty(el, "clientHeight", {
+ configurable: true,
+ writable: true,
+ value: metrics.clientHeight,
+ });
+ };
+
+ it("calls loadOlder when the user scrolls near the top", async () => {
+ const loadOlder = setupPaginationTest();
+ renderWithQueryClient(<ChatInterface />, queryClient);
+
+ const scrollContainer = document.querySelector(
+ ".custom-scrollbar-always",
+ ) as HTMLElement | null;
+ expect(scrollContainer).not.toBeNull();
+
+ // Pretend the user just scrolled near the top of an overflowing list.
+ setScrollMetrics(scrollContainer!, {
+ scrollTop: 0,
+ scrollHeight: 5000,
+ clientHeight: 800,
+ });
+ // Drop any on-mount auto-trigger so we exclusively assert the scroll path.
+ await new Promise((r) => {
+ setTimeout(r, 0);
+ });
+ loadOlder.mockClear();
+
+ fireEvent.scroll(scrollContainer!);
+
+ await new Promise((r) => {
+ setTimeout(r, 0);
+ });
+ expect(loadOlder).toHaveBeenCalledTimes(1);
+ });
+
+ it("auto-loads older events when the chat content does not overflow the viewport", async () => {
+ // No overflow β‡’ no scrollbar β‡’ user can't trigger loadOlder by
+ // scrolling. The component must auto-trigger via useEffect.
+ const loadOlder = setupPaginationTest();
+ renderWithQueryClient(<ChatInterface />, queryClient);
+
+ // Allow the on-mount auto-trigger useEffect to fire.
+ await new Promise((r) => {
+ setTimeout(r, 0);
+ });
+
+ expect(loadOlder).toHaveBeenCalled();
+ });
+
+ it("loads older events when the user wheels up while pinned at scrollTop=0", async () => {
+ // Overscroll-at-top: scrollTop is already 0 so the browser does not
+ // dispatch a scroll event. Wheel handler must catch this.
+ const loadOlder = setupPaginationTest();
+ renderWithQueryClient(<ChatInterface />, queryClient);
+
+ const scrollContainer = document.querySelector(
+ ".custom-scrollbar-always",
+ ) as HTMLElement | null;
+ expect(scrollContainer).not.toBeNull();
+
+ // Plenty of scrollable content overhead so the no-overflow branch
+ // doesn't claim the call β€” we want to exercise the wheel path.
+ setScrollMetrics(scrollContainer!, {
+ scrollTop: 0,
+ scrollHeight: 10000,
+ clientHeight: 800,
+ });
+
+ // Let any on-mount auto-trigger settle.
+ await new Promise((r) => {
+ setTimeout(r, 0);
+ });
+ loadOlder.mockClear();
+
+ // User is pinned at the top and wheels upward β€” no scroll event
+ // would fire here in a real browser.
+ fireEvent.wheel(scrollContainer!, { deltaY: -100 });
+
+ await new Promise((r) => {
+ setTimeout(r, 0);
+ });
+
+ expect(loadOlder).toHaveBeenCalledTimes(1);
+ });
+
+ it("shows an error banner if loading older events fails", async () => {
+ // This test exercises the real useLoadOlderEvents (so a rejected
+ // searchEvents propagates through to the chat's error banner).
+ // Override the global mock with the actual implementation.
+ const actualLoadOlderModule = await vi.importActual<
+ typeof import("#/hooks/use-load-older-events")
+ >("#/hooks/use-load-older-events");
+ vi.mocked(useLoadOlderEvents).mockImplementation(
+ actualLoadOlderModule.useLoadOlderEvents,
+ );
+
+ const seedEvent: MessageEvent = {
+ id: "msg-seed",
+ timestamp: "2025-07-01T00:00:00Z",
+ source: "user",
+ llm_message: {
+ role: "user",
+ content: [{ type: "text", text: "Existing message" }],
+ },
+ activated_microagents: [],
+ extended_content: [],
+ };
+ useEventStore.setState({
+ events: [seedEvent],
+ eventIds: new Set(["msg-seed"]),
+ uiEvents: [seedEvent],
+ });
+
+ const useUserConversationModule =
+ await import("#/hooks/query/use-user-conversation");
+ vi.spyOn(useUserConversationModule, "useUserConversation").mockReturnValue({
+ data: {
+ conversation_id: "test-conversation-id",
+ conversation_url: "https://example.com",
+ session_api_key: "k",
+ conversation_version: "V1",
+ },
+ isLoading: false,
+ isPending: false,
+ isError: false,
+ error: null,
+ refetch: vi.fn(),
+ } as unknown as ReturnType<
+ typeof useUserConversationModule.useUserConversation
+ >);
+
+ const eventServiceModule =
+ await import("#/api/event-service/event-service.api");
+ vi.spyOn(eventServiceModule.default, "searchEvents").mockRejectedValue(
+ new Error("Older events request failed"),
+ );
+
+ renderWithQueryClient(<ChatInterface />, queryClient);
+
+ const scrollContainer = document.querySelector(
+ ".custom-scrollbar-always",
+ ) as HTMLElement | null;
+ expect(scrollContainer).not.toBeNull();
+
+ Object.defineProperty(scrollContainer!, "scrollTop", {
+ configurable: true,
+ writable: true,
+ value: 0,
+ });
+ Object.defineProperty(scrollContainer!, "scrollHeight", {
+ configurable: true,
+ writable: true,
+ value: 5000,
+ });
+
+ scrollContainer!.dispatchEvent(new Event("scroll", { bubbles: true }));
+
+ expect(
+ await screen.findByText("Older events request failed"),
+ ).toBeInTheDocument();
+ });
+
+ it("renders renderable agent events even when the loaded window has no user message (so the user has something to scroll up from)", () => {
+ // Simulate the lazy-loaded "50 most recent" window landing in the
+ // store with only agent / environment events β€” the original user
+ // prompt is older than this window.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const agentAction: any = {
+ id: "act-1",
+ timestamp: "2025-07-01T00:00:10Z",
+ source: "agent",
+ kind: "ActionEvent",
+ action: {
+ kind: "ExecuteBashAction",
+ command: "ls",
+ },
+ tool_name: "terminal",
+ tool_call_id: "call-1",
+ tool_call: {
+ id: "call-1",
+ name: "terminal",
+ arguments: { command: "ls" },
+ },
+ llm_response_id: "resp-1",
+ thought: [],
+ reasoning_content: "",
+ thinking_blocks: [],
+ };
+
+ useEventStore.setState({
+ events: [agentAction],
+ eventIds: new Set(["act-1"]),
+ uiEvents: [agentAction],
+ });
+
+ renderWithQueryClient(<ChatInterface />, queryClient);
+
+ // The scroll container exists (so the user can scroll up to load older).
+ const scrollContainer = document.querySelector(
+ ".custom-scrollbar-always",
+ ) as HTMLElement | null;
+ expect(scrollContainer).not.toBeNull();
+
+ // ChatSuggestions should NOT take over the chat area when agent
+ // actions are present in the loaded window.
+ expect(screen.queryByTestId("chat-suggestions")).not.toBeInTheDocument();
+
+ // The Messages list should be rendered (the bug was that it was
+ // gated on `conversationUserEventsExist` and stayed hidden here,
+ // leaving a blank chat with nothing to scroll).
+ expect(scrollContainer!.children.length).toBeGreaterThan(0);
+ });
});
-describe('ChatInterface - Status Indicator', () => {
+describe("ChatInterface - Status Indicator", () => {
it("should render ChatStatusIndicator when agent is not awaiting user input / conversation is NOT ready", () => {
vi.mocked(useAgentState).mockReturnValue({
curAgentState: AgentState.LOADING,
@@ -208,6 +512,8 @@ describe('ChatInterface - Status Indicator', () => {
renderChatInterfaceWithRouter();
- expect(screen.queryByTestId("chat-status-indicator")).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("chat-status-indicator"),
+ ).not.toBeInTheDocument();
});
});
diff --git a/__tests__/components/chat/message-display-continuity.test.tsx b/__tests__/components/chat/message-display-continuity.test.tsx
index ca4208ac1f..1bea6f6c4e 100644
--- a/__tests__/components/chat/message-display-continuity.test.tsx
+++ b/__tests__/components/chat/message-display-continuity.test.tsx
@@ -161,11 +161,15 @@ describe("ChatInterface – message display continuity (spec 3.1)", () => {
renderWithQueryClient(<ChatInterface />, queryClient);
- // AC1: Messages should display immediately without skeleton
+ // AC1: Messages should display immediately without the full history
+ // skeleton, even if the lazy older-events pagination spinner appears.
expect(
screen.queryByTestId("chat-messages-skeleton"),
).not.toBeInTheDocument();
- expect(screen.queryByTestId("loading-spinner")).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("conversation-messages") ??
+ screen.queryByTestId("user-message"),
+ ).not.toBeNull();
});
it("shows skeleton when store is empty and loading", () => {
@@ -207,11 +211,14 @@ describe("ChatInterface – message display continuity (spec 3.1)", () => {
renderWithQueryClient(<ChatInterface />, queryClient);
- // Messages should display, no skeleton
+ // Messages should display without the full history skeleton.
expect(
screen.queryByTestId("chat-messages-skeleton"),
).not.toBeInTheDocument();
- expect(screen.queryByTestId("loading-spinner")).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("conversation-messages") ??
+ screen.queryByTestId("user-message"),
+ ).not.toBeNull();
});
});
});
diff --git a/__tests__/hooks/query/use-conversation-history.test.tsx b/__tests__/hooks/query/use-conversation-history.test.tsx
index aedf2b97ac..0b238a719d 100644
--- a/__tests__/hooks/query/use-conversation-history.test.tsx
+++ b/__tests__/hooks/query/use-conversation-history.test.tsx
@@ -3,11 +3,15 @@ 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 {
+ INITIAL_HISTORY_PAGE_SIZE,
+ 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/agent-server/core";
+import type { EventSearchPage } from "#/api/event-service/event-service.types";
function makeConversation(version: "V0" | "V1"): Conversation {
return {
@@ -26,10 +30,15 @@ function makeConversation(version: "V0" | "V1"): Conversation {
};
}
-function makeEvent(): OpenHandsEvent {
- return {
- id: "evt-1",
- } as OpenHandsEvent;
+function makeEvent(id = "evt-1", timestamp = "2024-01-01T00:00:00Z") {
+ return { id, timestamp } as unknown as OpenHandsEvent;
+}
+
+function makePage(
+ items: OpenHandsEvent[] = [],
+ nextPageId: string | null = null,
+): EventSearchPage<OpenHandsEvent> {
+ return { items, next_page_id: nextPageId };
}
// --------------------
@@ -44,7 +53,13 @@ vi.mock("#/api/open-hands-axios", () => ({
vi.mock("#/api/event-service/event-service.api");
vi.mock("#/hooks/query/use-user-conversation");
-const queryClient = new QueryClient();
+const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ },
+});
function wrapper({ children }: { children: React.ReactNode }) {
return (
@@ -60,7 +75,7 @@ describe("useConversationHistory", () => {
vi.clearAllMocks();
});
- it("calls V1 REST endpoint for V1 conversations", async () => {
+ it("requests the most recent INITIAL_HISTORY_PAGE_SIZE events sorted desc", async () => {
const v1SearchEventsSpy = vi.spyOn(EventService, "searchEvents");
vi.mocked(useUserConversation).mockReturnValue({
@@ -72,7 +87,7 @@ describe("useConversationHistory", () => {
refetch: vi.fn(),
} as any);
- v1SearchEventsSpy.mockResolvedValue([makeEvent()]);
+ v1SearchEventsSpy.mockResolvedValue(makePage([makeEvent()]));
const { result } = renderHook(() => useConversationHistory("conv-123"), {
wrapper,
@@ -82,17 +97,117 @@ describe("useConversationHistory", () => {
expect(result.current.data).toBeDefined();
});
- // searchEvents now accepts (conversationId, limit, conversationUrl,
- // sessionApiKey). The latter two are forwarded so cloud-mode calls
- // can target the correct host. In this test fixture they're null
- // (no conversation_url / session_api_key on the mocked conversation).
+ // Signature: (conversationId, conversationUrl, sessionApiKey, options).
+ // Initial load only fetches the tail (TIMESTAMP_DESC + page-size limit)
+ // so the user sees the most recent 50 events first.
expect(EventService.searchEvents).toHaveBeenCalledWith(
"conv-123",
- 100,
null,
null,
+ {
+ limit: INITIAL_HISTORY_PAGE_SIZE,
+ sortOrder: "TIMESTAMP_DESC",
+ },
+ );
+ });
+
+ it("returns events in chronological order even though the server returns desc", async () => {
+ vi.mocked(useUserConversation).mockReturnValue({
+ data: makeConversation("V1"),
+ isLoading: false,
+ isPending: false,
+ isError: false,
+ error: null,
+ refetch: vi.fn(),
+ } as any);
+
+ const newest = makeEvent("evt-newest", "2024-02-01T00:00:00Z");
+ const middle = makeEvent("evt-middle", "2024-01-15T00:00:00Z");
+ const oldest = makeEvent("evt-oldest", "2024-01-01T00:00:00Z");
+
+ vi.spyOn(EventService, "searchEvents").mockResolvedValue(
+ makePage([newest, middle, oldest], "page-2"),
+ );
+
+ const { result } = renderHook(() => useConversationHistory("conv-order"), {
+ wrapper,
+ });
+
+ await waitFor(() => {
+ expect(result.current.data).toBeDefined();
+ });
+
+ expect(result.current.data?.events.map((e: any) => e.id)).toEqual([
+ "evt-oldest",
+ "evt-middle",
+ "evt-newest",
+ ]);
+ expect(result.current.data?.hasMore).toBe(true);
+ expect(result.current.data?.nextPageId).toBe("page-2");
+ });
+
+ it("treats a full initial page without next_page_id as having more history", async () => {
+ vi.mocked(useUserConversation).mockReturnValue({
+ data: makeConversation("V1"),
+ isLoading: false,
+ isPending: false,
+ isError: false,
+ error: null,
+ refetch: vi.fn(),
+ } as any);
+
+ vi.spyOn(EventService, "searchEvents").mockResolvedValue(
+ makePage(
+ Array.from({ length: INITIAL_HISTORY_PAGE_SIZE }, (_, index) =>
+ makeEvent(`evt-${index}`, new Date(2024, 0, index + 1).toISOString()),
+ ),
+ null,
+ ),
+ );
+
+ const { result } = renderHook(
+ () => useConversationHistory("conv-full-page"),
+ {
+ wrapper,
+ },
+ );
+
+ await waitFor(() => {
+ expect(result.current.data).toBeDefined();
+ });
+
+ expect(result.current.data?.hasMore).toBe(true);
+ });
+
+ it("throws a descriptive error when searchEvents returns malformed items", async () => {
+ vi.mocked(useUserConversation).mockReturnValue({
+ data: makeConversation("V1"),
+ isLoading: false,
+ isPending: false,
+ isError: false,
+ error: null,
+ refetch: vi.fn(),
+ } as any);
+
+ vi.spyOn(EventService, "searchEvents").mockResolvedValue({
+ items: { bad: true },
+ next_page_id: null,
+ } as unknown as EventSearchPage<OpenHandsEvent>);
+
+ const { result } = renderHook(
+ () => useConversationHistory("conv-malformed"),
+ { wrapper },
+ );
+
+ await waitFor(() => {
+ expect(result.current.error).toBeInstanceOf(Error);
+ });
+
+ expect((result.current.error as Error).message).toBe(
+ "Invalid conversation history response: expected page.items to be an array.",
);
});
+
});
describe("useConversationHistory cache key stability", () => {
@@ -126,7 +241,7 @@ describe("useConversationHistory cache key stability", () => {
it("does not refetch when conversation object changes but version stays the same", async () => {
const v1Spy = vi.spyOn(EventService, "searchEvents");
- v1Spy.mockResolvedValue([makeEvent()]);
+ v1Spy.mockResolvedValue(makePage([makeEvent()]));
const conv1 = makeConversation("V1");
vi.mocked(useUserConversation).mockReturnValue({
@@ -183,7 +298,7 @@ describe("useConversationHistory cache key stability", () => {
it("treats cached history as never stale (staleTime is Infinity)", async () => {
const v1Spy = vi.spyOn(EventService, "searchEvents");
- v1Spy.mockResolvedValue([makeEvent()]);
+ v1Spy.mockResolvedValue(makePage([makeEvent()]));
vi.mocked(useUserConversation).mockReturnValue({
data: makeConversation("V1"),
@@ -215,7 +330,7 @@ describe("useConversationHistory cache key stability", () => {
it("has gcTime of at least 30 minutes for navigation resilience", async () => {
const v1Spy = vi.spyOn(EventService, "searchEvents");
- v1Spy.mockResolvedValue([makeEvent()]);
+ v1Spy.mockResolvedValue(makePage([makeEvent()]));
vi.mocked(useUserConversation).mockReturnValue({
data: makeConversation("V1"),
diff --git a/__tests__/hooks/use-load-older-events.test.tsx b/__tests__/hooks/use-load-older-events.test.tsx
new file mode 100644
index 0000000000..21a423dcf5
--- /dev/null
+++ b/__tests__/hooks/use-load-older-events.test.tsx
@@ -0,0 +1,321 @@
+import { describe, it, expect, afterEach, vi, beforeEach } from "vitest";
+import React from "react";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+
+import { useLoadOlderEvents } from "#/hooks/use-load-older-events";
+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 type { Conversation } from "#/api/open-hands.types";
+import type { OpenHandsEvent } from "#/types/agent-server/core";
+import type { EventSearchPage } from "#/api/event-service/event-service.types";
+
+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");
+
+function makeConversation(): Conversation {
+ // Cast: `useUserConversation` actually returns an `AppConversation` whose
+ // event-host URL lives on `conversation_url` (not the `Conversation.url`
+ // declared above). We mirror that shape here so the hook's call to
+ // `conversation.conversation_url` resolves.
+ 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,
+ conversation_url: "https://example.com/conv-test",
+ session_api_key: "secret",
+ conversation_version: "V1",
+ } as unknown as Conversation;
+}
+
+function makeEvent(id: string, timestamp: string): OpenHandsEvent {
+ return { id, timestamp } as unknown as OpenHandsEvent;
+}
+
+function makePage(
+ items: OpenHandsEvent[],
+ nextPageId: string | null = null,
+): EventSearchPage<OpenHandsEvent> {
+ return { items, next_page_id: nextPageId };
+}
+
+describe("useLoadOlderEvents", () => {
+ let queryClient: QueryClient;
+ let wrapper: ({
+ children,
+ }: {
+ children: React.ReactNode;
+ }) => React.ReactElement;
+
+ beforeEach(() => {
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ wrapper = ({ children }) =>
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ children,
+ );
+
+ // Reset event store between tests so prior tests don't leak state.
+ act(() => {
+ useEventStore.getState().clearEvents();
+ });
+
+ vi.mocked(useUserConversation).mockReturnValue({
+ data: makeConversation(),
+ isLoading: false,
+ isPending: false,
+ isError: false,
+ error: null,
+ refetch: vi.fn(),
+ } as any);
+ });
+
+ afterEach(() => {
+ queryClient.clear();
+ vi.clearAllMocks();
+ });
+
+ it("does nothing while the store has no anchor (REST hasn't seeded yet)", async () => {
+ const spy = vi.spyOn(EventService, "searchEvents");
+ const { result } = renderHook(() => useLoadOlderEvents("conv-1"), {
+ wrapper,
+ });
+
+ await act(async () => {
+ await result.current.loadOlder();
+ });
+
+ expect(spy).not.toHaveBeenCalled();
+ expect(result.current.hasMore).toBe(true);
+ });
+
+ it("paginates older events using timestamp__lt of the oldest known event", async () => {
+ // Seed the store with a single recent event so the hook has an anchor.
+ const recent = makeEvent("evt-recent", "2024-06-01T00:00:00Z");
+ act(() => {
+ useEventStore.getState().addEvent(recent);
+ });
+
+ const olderPage = [
+ makeEvent("evt-older-1", "2024-05-01T00:00:00Z"),
+ makeEvent("evt-older-2", "2024-05-15T00:00:00Z"),
+ ];
+ const spy = vi
+ .spyOn(EventService, "searchEvents")
+ .mockResolvedValue(makePage(olderPage, null));
+
+ const { result } = renderHook(() => useLoadOlderEvents("conv-1"), {
+ wrapper,
+ });
+
+ await act(async () => {
+ await result.current.loadOlder();
+ });
+
+ expect(spy).toHaveBeenCalledWith(
+ "conv-1",
+ "https://example.com/conv-test",
+ "secret",
+ {
+ limit: INITIAL_HISTORY_PAGE_SIZE,
+ sortOrder: "TIMESTAMP_DESC",
+ timestampLt: "2024-06-01T00:00:00Z",
+ },
+ );
+
+ // Older events landed in the store, in chronological order.
+ expect(useEventStore.getState().events.map((e) => (e as any).id)).toEqual([
+ "evt-older-1",
+ "evt-older-2",
+ "evt-recent",
+ ]);
+
+ // Server returned a short page β†’ no more pages to load.
+ await waitFor(() => {
+ expect(result.current.hasMore).toBe(false);
+ });
+ });
+
+ it("keeps paginating while the server keeps returning full pages", async () => {
+ act(() => {
+ useEventStore
+ .getState()
+ .addEvent(makeEvent("evt-recent", "2024-06-01T00:00:00Z"));
+ });
+
+ const fullPage: OpenHandsEvent[] = Array.from(
+ { length: INITIAL_HISTORY_PAGE_SIZE },
+ (_, i) =>
+ makeEvent(
+ `evt-page1-${i}`,
+ // Descending timestamps within the page so newest-first works.
+ new Date(2024, 4, 30 - i).toISOString(),
+ ),
+ );
+
+ vi.spyOn(EventService, "searchEvents").mockResolvedValue(
+ makePage(fullPage, "next-page"),
+ );
+
+ const { result } = renderHook(() => useLoadOlderEvents("conv-1"), {
+ wrapper,
+ });
+
+ await act(async () => {
+ await result.current.loadOlder();
+ });
+
+ // Full page + next_page_id present β†’ still has more.
+ expect(result.current.hasMore).toBe(true);
+ });
+
+ it("coalesces repeated loadOlder calls while a page request is already in flight", async () => {
+ act(() => {
+ useEventStore
+ .getState()
+ .addEvent(makeEvent("evt-recent", "2024-06-01T00:00:00Z"));
+ });
+
+ let resolvePage!: (page: EventSearchPage<OpenHandsEvent>) => void;
+ const pendingPage = new Promise<EventSearchPage<OpenHandsEvent>>(
+ (resolve) => {
+ resolvePage = resolve;
+ },
+ );
+
+ const spy = vi
+ .spyOn(EventService, "searchEvents")
+ .mockReturnValue(pendingPage);
+
+ const { result } = renderHook(() => useLoadOlderEvents("conv-1"), {
+ wrapper,
+ });
+
+ let firstLoad!: Promise<void>;
+ let secondLoad!: Promise<void>;
+ await act(async () => {
+ firstLoad = result.current.loadOlder();
+ secondLoad = result.current.loadOlder();
+ });
+
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(result.current.isLoading).toBe(true);
+
+ await act(async () => {
+ resolvePage(makePage([makeEvent("evt-older", "2024-05-01T00:00:00Z")], null));
+ await Promise.all([firstLoad, secondLoad]);
+ });
+
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it("cleans up loading state and rethrows when the page request fails", async () => {
+ act(() => {
+ useEventStore
+ .getState()
+ .addEvent(makeEvent("evt-recent", "2024-06-01T00:00:00Z"));
+ });
+
+ vi.spyOn(EventService, "searchEvents").mockRejectedValue(
+ new Error("request failed"),
+ );
+
+ const { result } = renderHook(() => useLoadOlderEvents("conv-1"), {
+ wrapper,
+ });
+
+ let thrown: unknown;
+ await act(async () => {
+ try {
+ await result.current.loadOlder();
+ } catch (error) {
+ thrown = error;
+ }
+ });
+
+ expect(thrown).toBeInstanceOf(Error);
+ expect((thrown as Error).message).toBe("request failed");
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.hasMore).toBe(true);
+ });
+
+ it("throws a descriptive error when searchEvents returns malformed items", async () => {
+ act(() => {
+ useEventStore
+ .getState()
+ .addEvent(makeEvent("evt-recent", "2024-06-01T00:00:00Z"));
+ });
+
+ vi.spyOn(EventService, "searchEvents").mockResolvedValue({
+ items: { bad: true },
+ next_page_id: null,
+ } as unknown as EventSearchPage<OpenHandsEvent>);
+
+ const { result } = renderHook(() => useLoadOlderEvents("conv-1"), {
+ wrapper,
+ });
+
+ let thrown: unknown;
+ await act(async () => {
+ try {
+ await result.current.loadOlder();
+ } catch (error) {
+ thrown = error;
+ }
+ });
+
+ expect(thrown).toBeInstanceOf(Error);
+ expect((thrown as Error).message).toBe(
+ "Invalid older-events response: expected page.items to be an array.",
+ );
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.hasMore).toBe(true);
+ });
+
+
+
+
+ it("stops paginating and throws when the oldest loaded event is missing a timestamp", async () => {
+ act(() => {
+ useEventStore
+ .getState()
+ .addEvent({ id: "evt-missing-ts" } as OpenHandsEvent);
+ });
+
+ const spy = vi.spyOn(EventService, "searchEvents");
+ const { result } = renderHook(() => useLoadOlderEvents("conv-1"), {
+ wrapper,
+ });
+
+ let thrown: unknown;
+ await act(async () => {
+ try {
+ await result.current.loadOlder();
+ } catch (error) {
+ thrown = error;
+ }
+ });
+
+ expect(spy).not.toHaveBeenCalled();
+ expect(thrown).toBeInstanceOf(Error);
+ expect((thrown as Error).message).toContain(
+ "oldest loaded event has no timestamp",
+ );
+ await waitFor(() => {
+ expect(result.current.hasMore).toBe(false);
+ });
+ });
+});
diff --git a/__tests__/stores/use-event-store.test.ts b/__tests__/stores/use-event-store.test.ts
index 5db692cce9..78adc9a38e 100644
--- a/__tests__/stores/use-event-store.test.ts
+++ b/__tests__/stores/use-event-store.test.ts
@@ -105,6 +105,67 @@ describe("useEventStore", () => {
]);
});
+ it("should bulk-add events and sort them chronologically", () => {
+ const { result } = renderHook(() => useEventStore());
+
+ const newest = {
+ id: "evt-newest",
+ timestamp: "2024-03-01T00:00:00Z",
+ source: "user",
+ } as any;
+ const middle = {
+ id: "evt-middle",
+ timestamp: "2024-02-01T00:00:00Z",
+ source: "user",
+ } as any;
+ const oldest = {
+ id: "evt-oldest",
+ timestamp: "2024-01-01T00:00:00Z",
+ source: "user",
+ } as any;
+
+ // Seed with the newest event, then bulk-prepend older ones (the
+ // pagination-on-scroll case). The store should re-sort chronologically.
+ act(() => {
+ result.current.addEvent(newest);
+ result.current.addEvents([oldest, middle]);
+ });
+
+ expect(result.current.events.map((e) => (e as any).id)).toEqual([
+ "evt-oldest",
+ "evt-middle",
+ "evt-newest",
+ ]);
+ });
+
+ it("should de-duplicate events on bulk add", () => {
+ const { result } = renderHook(() => useEventStore());
+
+ act(() => {
+ result.current.addEvent(mockUserMessageEvent);
+ result.current.addEvents([mockUserMessageEvent, mockActionEvent]);
+ });
+
+ expect(result.current.events).toHaveLength(2);
+ });
+
+ it("should apply action-to-observation UI replacement during bulk add", () => {
+ const { result } = renderHook(() => useEventStore());
+
+ act(() => {
+ result.current.addEvents([
+ mockUserMessageEvent,
+ mockActionEvent,
+ mockObservationEvent,
+ ]);
+ });
+
+ expect(result.current.uiEvents).toEqual([
+ mockUserMessageEvent,
+ mockObservationEvent,
+ ]);
+ });
+
it("should clear all events when clearEvents is called", () => {
const { result } = renderHook(() => useEventStore());
diff --git a/src/api/event-service/event-service.api.ts b/src/api/event-service/event-service.api.ts
index c74b8d2bfc..9cc94bb787 100644
--- a/src/api/event-service/event-service.api.ts
+++ b/src/api/event-service/event-service.api.ts
@@ -6,6 +6,8 @@ import { createHttpClient, createRemoteEventsList } from "../typescript-client";
import type {
ConfirmationResponseRequest,
ConfirmationResponseResponse,
+ EventSearchOptions,
+ EventSearchPage,
} from "./event-service.types";
/**
@@ -85,25 +87,40 @@ class EventService {
}).count();
}
+ /**
+ * Search events for a conversation. Returns the raw page so callers can
+ * paginate (via `next_page_id`) and so REST-driven history loading can
+ * tell when there are no more older events to load.
+ */
static async searchEvents(
conversationId: string,
- limit = 100,
conversationUrl?: string | null,
sessionApiKey?: string | null,
- ) {
+ options: EventSearchOptions = {},
+ ): Promise<EventSearchPage<OpenHandsEvent>> {
const active = getActiveBackend().backend;
+ const limit = options.limit ?? 100;
if (active.kind === "cloud") {
// Event *history* lives on the SaaS App API, not the runtime
// sandbox. Path is singular `conversation` and v1-prefixed.
const params = new URLSearchParams();
params.set("limit", String(limit));
- const data = await callCloudProxy<{ items?: OpenHandsEvent[] }>({
+ 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);
+
+ const data = await callCloudProxy<EventSearchPage<OpenHandsEvent>>({
backend: active,
method: "GET",
path: `/api/v1/conversation/${conversationId}/events/search?${params.toString()}`,
});
- return data?.items ?? [];
+ return {
+ items: data?.items ?? [],
+ next_page_id: data?.next_page_id ?? null,
+ };
}
const page = await createRemoteEventsList(conversationId, {
@@ -111,9 +128,16 @@ class EventService {
sessionApiKey,
}).search({
limit,
+ ...(options.pageId ? { page_id: options.pageId } : {}),
+ ...(options.sortOrder ? { sort_order: options.sortOrder } : {}),
+ ...(options.timestampGte ? { timestamp__gte: options.timestampGte } : {}),
+ ...(options.timestampLt ? { timestamp__lt: options.timestampLt } : {}),
});
- return (page.items ?? []) as OpenHandsEvent[];
+ return {
+ items: (page.items ?? []) as OpenHandsEvent[],
+ next_page_id: page.next_page_id ?? null,
+ };
}
}
diff --git a/src/api/event-service/event-service.types.ts b/src/api/event-service/event-service.types.ts
index 84c447f3e7..4b87963f50 100644
--- a/src/api/event-service/event-service.types.ts
+++ b/src/api/event-service/event-service.types.ts
@@ -6,3 +6,23 @@ export interface ConfirmationResponseRequest {
export interface ConfirmationResponseResponse {
success: boolean;
}
+
+export type EventSortOrder = "TIMESTAMP" | "TIMESTAMP_DESC";
+
+export interface EventSearchOptions {
+ /** Maximum number of events to return per page (server caps at 100). */
+ limit?: number;
+ /** Page ID for pagination. */
+ pageId?: string;
+ /** Sort order for the underlying server query. */
+ sortOrder?: EventSortOrder;
+ /** Filter: event timestamp >= this value (ISO 8601). */
+ timestampGte?: string;
+ /** Filter: event timestamp < this value (ISO 8601). */
+ timestampLt?: string;
+}
+
+export interface EventSearchPage<TEvent> {
+ items: TEvent[];
+ next_page_id?: string | null;
+}
diff --git a/src/components/features/chat/chat-interface.tsx b/src/components/features/chat/chat-interface.tsx
index a059d78a71..1041e93a3d 100644
--- a/src/components/features/chat/chat-interface.tsx
+++ b/src/components/features/chat/chat-interface.tsx
@@ -8,6 +8,7 @@ import { InteractiveChatBox } from "./interactive-chat-box";
import { AgentState } from "#/types/agent-state";
import { useFilteredEvents } from "#/hooks/use-filtered-events";
import { useScrollToBottom } from "#/hooks/use-scroll-to-bottom";
+import { useLoadOlderEvents } from "#/hooks/use-load-older-events";
import { TypingIndicator } from "./typing-indicator";
import { ChatSuggestions } from "./chat-suggestions";
import { ScrollProvider } from "#/context/scroll-context";
@@ -48,7 +49,8 @@ function getEntryPoint(
export function ChatInterface() {
const posthog = usePostHog();
const { setMessageToSend } = useConversationStore();
- const { errorMessage, removeErrorMessage } = useErrorMessageStore();
+ const { errorMessage, removeErrorMessage, setErrorMessage } =
+ useErrorMessageStore();
const { isTask, taskStatus, taskDetail } = useTaskPolling();
const conversationWebSocket = useConversationWebSocket();
const { send } = useSendMessage();
@@ -57,7 +59,6 @@ export function ChatInterface() {
allConversationEvents,
totalEvents,
hasSubstantiveAgentActions,
- conversationUserEventsExist,
userEventsExist,
} = useFilteredEvents();
const { setOptimisticUserMessage, getOptimisticUserMessage } =
@@ -114,6 +115,69 @@ export function ChatInterface() {
const { conversationId } = useOptionalConversationId();
const { mutateAsync: uploadFiles } = useUnifiedUploadFiles();
+ // Lazy "scroll up to load older events" backfill. Initial REST fetch only
+ // returns the most recent page; this hook paginates older events into the
+ // store on demand so the chat doesn't load (potentially) thousands of
+ // events on first render.
+ const {
+ isLoading: isLoadingOlderEvents,
+ hasMore: hasMoreOlderEvents,
+ loadOlder,
+ } = useLoadOlderEvents(conversationId);
+
+ // Trigger `loadOlder` and preserve the visual scroll position once the
+ // older page is merged in (otherwise prepending events would jump the
+ // chat far down). We fire from three places to cover the cases the
+ // browser's scroll event misses:
+ //
+ // - `onScroll`: normal "user scrolled near the top" path.
+ // - `onWheel`: user is already pinned at scrollTop=0 and tries to
+ // wheel further up β€” no scroll event fires past 0.
+ // - effect: content is shorter than the viewport (no scrollbar
+ // at all), so the user has nothing to scroll. Re-runs
+ // as more pages arrive until there's overflow or the
+ // server runs out of older events.
+ const SCROLL_TOP_THRESHOLD_PX = 80;
+ const preserveScrollPosition = React.useRef<{
+ scrollHeight: number;
+ scrollTop: number;
+ } | null>(null);
+ const maybeLoadOlder = React.useCallback(
+ (target: HTMLElement) => {
+ if (isLoadingOlderEvents || !hasMoreOlderEvents) return;
+
+ const atTop = target.scrollTop <= SCROLL_TOP_THRESHOLD_PX;
+ const noOverflow =
+ target.scrollHeight <= target.clientHeight + SCROLL_TOP_THRESHOLD_PX;
+ if (!atTop && !noOverflow) return;
+
+ preserveScrollPosition.current = {
+ scrollHeight: target.scrollHeight,
+ scrollTop: target.scrollTop,
+ };
+ loadOlder().catch((error) => {
+ preserveScrollPosition.current = null;
+ const message =
+ error instanceof Error && error.message
+ ? error.message
+ : t(I18nKey.ERROR$GENERIC);
+ setErrorMessage(message);
+ });
+ },
+ [hasMoreOlderEvents, isLoadingOlderEvents, loadOlder, setErrorMessage, t],
+ );
+
+ const handleWheelForPagination = React.useCallback(
+ (e: React.WheelEvent<HTMLDivElement>) => {
+ // Browsers don't dispatch a scroll event when scrollTop is already
+ // 0 and the user wheels upward, so onScroll alone misses this case.
+ if (e.deltaY < 0 && e.currentTarget.scrollTop <= 0) {
+ maybeLoadOlder(e.currentTarget);
+ }
+ },
+ [maybeLoadOlder],
+ );
+
const optimisticUserMessage = getOptimisticUserMessage();
// Show V1 messages immediately if events exist in store (e.g., remount),
@@ -207,8 +271,25 @@ export function ChatInterface() {
setMessageToSend("");
};
- // Auto-scroll to bottom when new messages arrive
+ // Auto-scroll to bottom when new messages arrive β€” but only if the user is
+ // already pinned to the bottom. Scrolling up to load older events also
+ // grows `renderableEvents`, and we don't want to yank the user back to the
+ // bottom in that case.
React.useEffect(() => {
+ // If a "load older" was just triggered, restore the scroll position so
+ // the conversation appears to extend upward instead of jumping.
+ if (preserveScrollPosition.current && scrollRef.current) {
+ const { scrollHeight: prevHeight, scrollTop: prevTop } =
+ preserveScrollPosition.current;
+ const dom = scrollRef.current;
+ const delta = dom.scrollHeight - prevHeight;
+ if (delta > 0) {
+ dom.scrollTop = prevTop + delta;
+ }
+ preserveScrollPosition.current = null;
+ return;
+ }
+
if (autoScroll) {
scrollDomToBottom();
}
@@ -217,6 +298,26 @@ export function ChatInterface() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [renderableEvents.length, optimisticUserMessage, scrollDomToBottom]);
+ // Auto-load older events when the chat content doesn't overflow the
+ // scroll area (no scrollbar to drag, no wheel events past 0). We
+ // re-run only when the rendered list grows or `hasMore` flips, NOT
+ // when `maybeLoadOlder` re-creates: the underlying hook's `loadOlder`
+ // ref changes whenever its internal `isLoading` toggles, so depending
+ // on `maybeLoadOlder` would re-fire the effect on every failed page
+ // and tight-loop until the server recovered. Driving off
+ // `renderableEvents.length` instead means a successful page (events
+ // grow) chains the next request, while a failed page (events
+ // unchanged) waits for the user to retry.
+ const maybeLoadOlderRef = React.useRef(maybeLoadOlder);
+ React.useEffect(() => {
+ maybeLoadOlderRef.current = maybeLoadOlder;
+ });
+ React.useEffect(() => {
+ const target = scrollRef.current;
+ if (!target) return;
+ maybeLoadOlderRef.current(target);
+ }, [renderableEvents.length, hasMoreOlderEvents]);
+
// Create a ScrollProvider with the scroll hook values
const scrollProviderValue = {
scrollRef,
@@ -268,7 +369,11 @@ export function ChatInterface() {
<div
ref={scrollRef}
- onScroll={(e) => onChatBodyScroll(e.currentTarget)}
+ onScroll={(e) => {
+ onChatBodyScroll(e.currentTarget);
+ maybeLoadOlder(e.currentTarget);
+ }}
+ onWheel={handleWheelForPagination}
className="custom-scrollbar-always flex flex-col grow overflow-y-auto overflow-x-hidden px-4 pt-4 gap-2"
>
{isChatLoading && isReturningToConversation && (
@@ -281,7 +386,27 @@ export function ChatInterface() {
</div>
)}
- {showConversationMessages && conversationUserEventsExist && (
+ {isLoadingOlderEvents && (
+ <div
+ className="flex justify-center py-2"
+ data-testid="loading-older-events"
+ >
+ <LoadingSpinner size="small" />
+ </div>
+ )}
+
+ {/*
+ * Render whenever there's anything to display. Previously this
+ * was gated on `conversationUserEventsExist`, but with the lazy
+ * "50 most recent" REST fetch the initial window may not include
+ * any `source: "user"` events (long agent runs between user
+ * turns). That left the chat blank, leaving the user nothing to
+ * scroll β€” which is why "scroll up to load older" appeared
+ * broken. The empty-state ChatSuggestions block above still
+ * keeps its own gate (`!userEventsExist && !hasSubstantiveAgentActions`)
+ * so brand-new conversations show suggestions, not an empty chat.
+ */}
+ {showConversationMessages && renderableEvents.length > 0 && (
<Messages
messages={renderableEvents}
allEvents={allConversationEvents}
diff --git a/src/contexts/conversation-websocket-context.tsx b/src/contexts/conversation-websocket-context.tsx
index 2c86eebaca..cf1c96fc46 100644
--- a/src/contexts/conversation-websocket-context.tsx
+++ b/src/contexts/conversation-websocket-context.tsx
@@ -101,19 +101,20 @@ export function ConversationWebSocketProvider({
const posthog = usePostHog();
const queryClient = useQueryClient();
- const { addEvent } = useEventStore();
+ const addEvent = useEventStore((state) => state.addEvent);
+ const addEvents = useEventStore((state) => state.addEvents);
const { setErrorMessage, removeErrorMessage } = useErrorMessageStore();
const { removeOptimisticUserMessage } = useOptimisticUserMessageStore();
const { setExecutionStatus } = useConversationStateStore();
const { appendInput, appendOutput } = useCommandStore();
- // History loading state - separate per connection
- const [isLoadingHistoryMain, setIsLoadingHistoryMain] = useState(true);
+ // History loading state.
+ // - Main conversation history is now loaded via REST (`useConversationHistory`),
+ // so its loading state mirrors the REST query state (see below).
+ // - Planning sub-conversation history still streams over the WebSocket using
+ // `resend_mode='all'`, so we keep the count-based detection for it.
const [isLoadingHistoryPlanning, setIsLoadingHistoryPlanning] =
useState(true);
- const [expectedEventCountMain, setExpectedEventCountMain] = useState<
- number | null
- >(null);
const [expectedEventCountPlanning, setExpectedEventCountPlanning] = useState<
number | null
>(null);
@@ -123,8 +124,7 @@ export function ConversationWebSocketProvider({
// Hook for reading conversation file
const { mutate: readConversationFile } = useReadConversationFile();
- // Separate received event count tracking per connection
- const receivedEventCountRefMain = useRef(0);
+ // Track planning-agent received events (still WS-driven).
const receivedEventCountRefPlanning = useRef(0);
// Track the latest PlanningFileEditorObservation for Plan.md during history replay
@@ -171,16 +171,64 @@ export function ConversationWebSocketProvider({
[],
);
- // Build WebSocket URL from props
- // Only build URL if we have both conversationId and conversationUrl
- // This prevents connection attempts during task polling phase
+ // Initial REST history load: fetch the most recent events and seed the
+ // store. Older events are paginated in via `useLoadOlderEvents` when the
+ // user scrolls to the top of the chat. The WebSocket connection waits for
+ // this query so it can subscribe with `resend_mode='since'` and avoid
+ // re-streaming everything REST already returned.
+ const {
+ data: preloadedHistory,
+ isPending: isPreloadingHistory,
+ isError: isPreloadHistoryError,
+ } = useConversationHistory(conversationId);
+
+ const isLoadingHistoryMain = !!conversationId && isPreloadingHistory;
+
+ useEffect(() => {
+ if (!preloadedHistory || preloadedHistory.events.length === 0) {
+ return;
+ }
+ addEvents(preloadedHistory.events);
+ }, [preloadedHistory, addEvents]);
+
+ /**
+ * Timestamp of the latest event we already have from REST. Used as
+ * `after_timestamp` when opening the WebSocket so the server only resends
+ * events strictly after this point. `null` until the REST query settles
+ * (we hold the WS connection open until then to avoid an `all` resend).
+ */
+ const initialAfterTimestamp = useMemo<string | null>(() => {
+ if (isPreloadingHistory) return null;
+ const events = preloadedHistory?.events ?? [];
+ const latest = events[events.length - 1];
+ if (!latest || !("timestamp" in latest) || !latest.timestamp) return null;
+ return latest.timestamp;
+ }, [preloadedHistory, isPreloadingHistory]);
+
+ // Build WebSocket URL from props.
+ //
+ // We deliberately wait for the initial REST history fetch to settle before
+ // opening the socket so the WS subscription can use `resend_mode='since'`
+ // with a meaningful `after_timestamp`. Without this gate, the WS would open
+ // immediately and either replay the entire conversation (when falling back
+ // to `resend_mode='all'`) or miss events that arrived between REST and WS.
const wsUrl = useMemo(() => {
- // Don't attempt connection if we're missing required data
if (!conversationId || !conversationUrl) {
return null;
}
+ // Don't connect while we're still fetching the initial history. If the
+ // REST query errored we fall through and connect with `resend_mode='all'`
+ // so the user still sees live events.
+ if (isPreloadingHistory && !isPreloadHistoryError) {
+ return null;
+ }
return buildWebSocketUrl(conversationId, conversationUrl);
- }, [conversationId, conversationUrl]);
+ }, [
+ conversationId,
+ conversationUrl,
+ isPreloadingHistory,
+ isPreloadHistoryError,
+ ]);
const planningAgentWsUrl = useMemo(() => {
if (!subConversations?.length) {
@@ -243,16 +291,6 @@ export function ConversationWebSocketProvider({
return "CLOSED";
}, [mainConnectionState, planningConnectionState, planningAgentWsUrl]);
- useEffect(() => {
- if (
- expectedEventCountMain !== null &&
- receivedEventCountRefMain.current >= expectedEventCountMain &&
- isLoadingHistoryMain
- ) {
- setIsLoadingHistoryMain(false);
- }
- }, [expectedEventCountMain, isLoadingHistoryMain, receivedEventCountRefMain]);
-
useEffect(() => {
if (
expectedEventCountPlanning !== null &&
@@ -303,36 +341,19 @@ export function ConversationWebSocketProvider({
latestPlanningFileEventRef.current = null;
}, [subConversationIds]);
- // Merged loading history state - true if either connection is still loading
- const isLoadingHistory = useMemo(
- () => isLoadingHistoryMain || isLoadingHistoryPlanning,
- [isLoadingHistoryMain, isLoadingHistoryPlanning],
- );
-
- // Reset hasConnected flags and history loading state when conversation changes
+ // Reset hasConnected flags when the conversation changes.
useEffect(() => {
+ hasConnectedRefMain.current = false;
hasConnectedRefPlanning.current = false;
- setIsLoadingHistoryMain(true);
- setExpectedEventCountMain(null);
- receivedEventCountRefMain.current = 0;
// Reset the tracked event ref when conversation changes
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]);
+ // Merged loading history state - true if either connection is still loading
+ const isLoadingHistory = useMemo(
+ () => isLoadingHistoryMain || isLoadingHistoryPlanning,
+ [isLoadingHistoryMain, isLoadingHistoryPlanning],
+ );
// Separate message handlers for each connection
const handleMainMessage = useCallback(
@@ -340,18 +361,8 @@ export function ConversationWebSocketProvider({
try {
const event = JSON.parse(messageEvent.data);
- // Track received events for history loading (count ALL events from WebSocket)
- // Always count when loading, even if we don't have the expected count yet
- if (isLoadingHistoryMain) {
- receivedEventCountRefMain.current += 1;
-
- if (
- expectedEventCountMain !== null &&
- receivedEventCountRefMain.current >= expectedEventCountMain
- ) {
- setIsLoadingHistoryMain(false);
- }
- }
+ // History loading for the main conversation is REST-driven now;
+ // every WS message is a new event we add to the store.
// Use type guard to validate v1 event structure
if (isAgentServerEvent(event)) {
@@ -464,8 +475,6 @@ export function ConversationWebSocketProvider({
},
[
addEvent,
- isLoadingHistoryMain,
- expectedEventCountMain,
setErrorMessage,
removeOptimisticUserMessage,
queryClient,
@@ -656,9 +665,15 @@ export function ConversationWebSocketProvider({
// Separate WebSocket options for main connection
const mainWebsocketOptions: WebSocketHookOptions = useMemo(() => {
- const queryParams: Record<string, string | boolean> = {
- resend_all: true,
- };
+ // History was already loaded over REST (`useConversationHistory`).
+ // Subscribe with `resend_mode='since'` so the server only resends events
+ // strictly after the latest one we already have. If REST returned no
+ // events at all (brand-new conversation), fall back to `'all'` so any
+ // events that may have been written between the REST call and the WS
+ // handshake still show up. Dedup in the event store handles overlap.
+ const queryParams: Record<string, string | boolean> = initialAfterTimestamp
+ ? { resend_mode: "since", after_timestamp: initialAfterTimestamp }
+ : { resend_mode: "all" };
// Add session_api_key if available
if (sessionApiKey) {
@@ -668,30 +683,10 @@ export function ConversationWebSocketProvider({
return {
queryParams,
reconnect: { enabled: true },
- onOpen: async () => {
+ onOpen: () => {
setMainConnectionState("OPEN");
hasConnectedRefMain.current = true; // Mark that we've successfully connected
removeErrorMessage(); // Clear any previous error messages on successful connection
-
- // Fetch expected event count for history loading detection
- if (conversationId && conversationUrl) {
- try {
- const count = await EventService.getEventCount(
- conversationId,
- conversationUrl,
- sessionApiKey,
- );
- setExpectedEventCountMain(count);
-
- // If no events expected, mark as loaded immediately
- if (count === 0) {
- setIsLoadingHistoryMain(false);
- }
- } catch (error) {
- // Fall back to marking as loaded to avoid infinite loading state
- setIsLoadingHistoryMain(false);
- }
- }
},
onClose: () => {
setMainConnectionState("CLOSED");
@@ -710,8 +705,7 @@ export function ConversationWebSocketProvider({
setErrorMessage,
removeErrorMessage,
sessionApiKey,
- conversationId,
- conversationUrl,
+ initialAfterTimestamp,
]);
// Separate WebSocket options for planning agent connection
diff --git a/src/hooks/query/use-conversation-history.ts b/src/hooks/query/use-conversation-history.ts
index 8bfe83b201..a3e7228fcf 100644
--- a/src/hooks/query/use-conversation-history.ts
+++ b/src/hooks/query/use-conversation-history.ts
@@ -1,11 +1,36 @@
import { useQuery } from "@tanstack/react-query";
import EventService from "#/api/event-service/event-service.api";
import { useUserConversation } from "#/hooks/query/use-user-conversation";
+import type { OpenHandsEvent } from "#/types/agent-server/core";
+/**
+ * Number of events to load on the initial REST history fetch and on each
+ * subsequent "scroll-up" page. The agent server caps `limit` at 100.
+ */
+export const INITIAL_HISTORY_PAGE_SIZE = 50;
+
+export interface ConversationHistoryPage {
+ /** Events in chronological (oldest β†’ newest) order. */
+ events: OpenHandsEvent[];
+ /** True when the server has more events older than this page. */
+ hasMore: boolean;
+ /** Optional `next_page_id` from the server for keyset pagination. */
+ nextPageId: string | null;
+}
+
+/**
+ * Loads the most recent conversation events via REST. The server query is
+ * sorted `TIMESTAMP_DESC` so we can request just the tail of the conversation;
+ * we reverse the result to chronological order before handing it to callers.
+ *
+ * Older events are loaded on demand by `useLoadOlderEvents` once the user
+ * scrolls up. The WebSocket then connects with `resend_mode='since'` using
+ * the latest event's timestamp so we don't re-receive history we already have.
+ */
export const useConversationHistory = (conversationId?: string) => {
const { data: conversation } = useUserConversation(conversationId ?? null);
- return useQuery({
+ return useQuery<ConversationHistoryPage>({
queryKey: [
"conversation-history",
conversationId,
@@ -16,17 +41,34 @@ export const useConversationHistory = (conversationId?: string) => {
],
enabled: !!conversationId && !!conversation,
queryFn: async () => {
- if (!conversationId) return [];
+ if (!conversationId) {
+ return { events: [], hasMore: false, nextPageId: null };
+ }
- // Forward the conversation's owning host + session key so cloud
- // conversations hit their cloud sandbox instead of falling back
- // to the bundled local agent-server.
- return EventService.searchEvents(
+ const page = await EventService.searchEvents(
conversationId,
- 100,
conversation?.conversation_url ?? null,
conversation?.session_api_key ?? null,
+ {
+ limit: INITIAL_HISTORY_PAGE_SIZE,
+ sortOrder: "TIMESTAMP_DESC",
+ },
);
+
+ if (!Array.isArray(page.items)) {
+ throw new Error(
+ "Invalid conversation history response: expected page.items to be an array.",
+ );
+ }
+
+ // Reverse so callers can append in chronological order.
+ const events = [...page.items].reverse();
+ return {
+ events,
+ hasMore:
+ !!page.next_page_id || page.items.length >= INITIAL_HISTORY_PAGE_SIZE,
+ nextPageId: page.next_page_id ?? null,
+ };
},
staleTime: Infinity,
gcTime: 30 * 60 * 1000, // 30 minutes β€” survive navigation away and back (AC5)
diff --git a/src/hooks/use-load-older-events.ts b/src/hooks/use-load-older-events.ts
new file mode 100644
index 0000000000..d13251f082
--- /dev/null
+++ b/src/hooks/use-load-older-events.ts
@@ -0,0 +1,114 @@
+import React from "react";
+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 type { OpenHandsEvent } from "#/types/agent-server/core";
+
+const getEventTimestamp = (event: OpenHandsEvent): string | undefined =>
+ "timestamp" in event ? event.timestamp : undefined;
+
+interface UseLoadOlderEventsResult {
+ /** True while a "load older" request is in flight. */
+ isLoading: boolean;
+ /**
+ * Whether the server may have more events older than what we currently
+ * have in the store. Starts `true` and flips to `false` after the server
+ * returns a short page (i.e. it ran out of older events).
+ */
+ hasMore: boolean;
+ /** Trigger one more older-events page. Resolves when the page is merged. */
+ loadOlder: () => Promise<void>;
+}
+
+/**
+ * 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.
+ */
+export const useLoadOlderEvents = (
+ conversationId?: string | null,
+): UseLoadOlderEventsResult => {
+ const { data: conversation } = useUserConversation(conversationId ?? null);
+ const addEvents = useEventStore((state) => state.addEvents);
+
+ const [isLoading, setIsLoading] = React.useState(false);
+ const [hasMore, setHasMore] = React.useState(true);
+ const isLoadingRef = React.useRef(false);
+ const hasMoreRef = React.useRef(true);
+
+ // Reset the pagination cursor whenever we switch conversations.
+ React.useEffect(() => {
+ hasMoreRef.current = true;
+ isLoadingRef.current = false;
+ setHasMore(true);
+ setIsLoading(false);
+ }, [conversationId]);
+
+ const loadOlder = React.useCallback(async () => {
+ if (!conversationId || isLoadingRef.current || !hasMoreRef.current) {
+ return;
+ }
+
+ const { events } = useEventStore.getState();
+ const oldest = events[0];
+
+ // No anchor yet β€” defer until the initial REST load has populated the
+ // store (avoids fetching twice with the same `TIMESTAMP_DESC` window).
+ if (!oldest) return;
+
+ const oldestTimestamp = getEventTimestamp(oldest);
+ if (!oldestTimestamp) {
+ hasMoreRef.current = false;
+ setHasMore(false);
+ throw new Error(
+ "Unable to load older events because the oldest loaded event has no timestamp.",
+ );
+ }
+
+ isLoadingRef.current = true;
+ setIsLoading(true);
+ try {
+ const page = await EventService.searchEvents(
+ conversationId,
+ conversation?.conversation_url ?? null,
+ conversation?.session_api_key ?? null,
+ {
+ limit: INITIAL_HISTORY_PAGE_SIZE,
+ sortOrder: "TIMESTAMP_DESC",
+ timestampLt: oldestTimestamp,
+ },
+ );
+
+ if (!Array.isArray(page.items)) {
+ throw new Error(
+ "Invalid older-events response: expected page.items to be an array.",
+ );
+ }
+
+ const older = [...page.items].reverse();
+ if (older.length > 0) {
+ addEvents(older);
+ }
+ // Stop once the server signals there are no more pages, OR β€” for
+ // servers that don't fill in `next_page_id` for filtered queries β€”
+ // when we get back a short page.
+ const exhausted =
+ !page.next_page_id || page.items.length < INITIAL_HISTORY_PAGE_SIZE;
+ if (exhausted) {
+ hasMoreRef.current = false;
+ setHasMore(false);
+ }
+ } finally {
+ isLoadingRef.current = false;
+ setIsLoading(false);
+ }
+ }, [
+ conversationId,
+ conversation?.conversation_url,
+ conversation?.session_api_key,
+ addEvents,
+ ]);
+
+ return { isLoading, hasMore, loadOlder };
+};
diff --git a/src/stores/use-event-store.ts b/src/stores/use-event-store.ts
index 53ee8c10a8..6abd6c81d5 100644
--- a/src/stores/use-event-store.ts
+++ b/src/stores/use-event-store.ts
@@ -52,44 +52,96 @@ export interface EventState {
eventIds: Set<string | number>;
uiEvents: OHEvent[];
addEvent: (event: OHEvent) => void;
+ /**
+ * Bulk-insert events. Used for the initial REST history load and for
+ * "scroll up to load older" pagination. Newly-added events are de-duped
+ * against the existing store and the combined list is re-sorted by
+ * timestamp so older pages drop into the correct position.
+ */
+ addEvents: (events: OHEvent[]) => void;
clearEvents: () => void;
}
+const appendEvent = (state: EventState, event: OHEvent): EventState => {
+ // 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 newEventIds =
+ eventId !== undefined
+ ? new Set(state.eventIds).add(eventId)
+ : state.eventIds;
+
+ return {
+ ...state,
+ events: [...state.events, event],
+ eventIds: newEventIds,
+ uiEvents: handleEventForUI(event, state.uiEvents),
+ };
+};
+
+const sortEventState = (state: EventState): EventState => ({
+ ...state,
+ events: [...state.events].sort(compareEventsByTimestamp),
+ uiEvents: [...state.uiEvents].sort(compareEventsByTimestamp),
+});
+
+const applyAddEvent = (state: EventState, event: OHEvent): EventState => {
+ const next = appendEvent(state, event);
+ if (next === state) {
+ return state;
+ }
+
+ if (
+ !needsSorting(state.events, event) &&
+ !needsSorting(state.uiEvents, event)
+ ) {
+ return next;
+ }
+
+ return sortEventState(next);
+};
+
export const useEventStore = create<EventState>()((set) => ({
events: [],
eventIds: new Set(),
uiEvents: [],
- addEvent: (event: OHEvent) =>
+ addEvent: (event: OHEvent) => set((state) => applyAddEvent(state, event)),
+ addEvents: (incoming: 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;
+ if (incoming.length === 0) return state;
+
+ const eventIds = new Set(state.eventIds);
+ const events = [...state.events];
+ let uiEvents = [...state.uiEvents];
+ let added = false;
+
+ for (const event of incoming) {
+ const eventId = getEventId(event);
+ const isDuplicate = eventId !== undefined && eventIds.has(eventId);
+
+ if (!isDuplicate) {
+ added = true;
+ if (eventId !== undefined) {
+ eventIds.add(eventId);
+ }
+ events.push(event);
+ uiEvents = handleEventForUI(event, uiEvents);
+ }
}
- // Add event and sort if needed to maintain chronological order
- let newEvents = [...state.events, event];
- if (needsSorting(state.events, event)) {
- newEvents = newEvents.sort(compareEventsByTimestamp);
- }
-
- const newEventIds =
- eventId !== undefined
- ? new Set(state.eventIds).add(eventId)
- : state.eventIds;
-
- // Process UI events and sort if needed
- let newUiEvents = handleEventForUI(event, state.uiEvents);
-
- if (needsSorting(state.uiEvents, event)) {
- newUiEvents = newUiEvents.sort(compareEventsByTimestamp);
+ if (!added) {
+ return state;
}
- return {
- events: newEvents,
- eventIds: newEventIds,
- uiEvents: newUiEvents,
- };
+ return sortEventState({
+ ...state,
+ events,
+ eventIds,
+ uiEvents,
+ });
}),
clearEvents: () =>
set(() => ({