Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: prevent stale conversation history merges (#16913)

Aditi Bhagat884372178d42
diff --git a/__tests__/components/chat/chat-interface.test.tsx b/__tests__/components/chat/chat-interface.test.tsx
index 119c57052b..4cd159a818 100644
--- a/__tests__/components/chat/chat-interface.test.tsx
+++ b/__tests__/components/chat/chat-interface.test.tsx
@@ -332,6 +332,7 @@ describe("ChatInterface - Scroll-up loads older events", () => {
events: [],
eventIds: new Set(),
uiEvents: [],
+ loadedConversationId: null,
});
vi.clearAllMocks();
});
@@ -360,6 +361,7 @@ describe("ChatInterface - Scroll-up loads older events", () => {
events: [seedEvent],
eventIds: new Set(["msg-seed"]),
uiEvents: [seedEvent],
+ loadedConversationId: "test-conversation-id",
});
return loadOlder;
};
@@ -421,6 +423,72 @@ describe("ChatInterface - Scroll-up loads older events", () => {
expect(loadOlder).toHaveBeenCalledTimes(1);
});
+ it("does not restore scroll geometry saved by a previous conversation", async () => {
+ const loadOlder = setupPaginationTest();
+ const renderChat = () => (
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter>
+ <ChatInterface />
+ </MemoryRouter>
+ </QueryClientProvider>
+ );
+ const view = render(renderChat());
+
+ const scrollContainer = document.querySelector(
+ "[data-testid='chat-scroll-container']",
+ ) as HTMLElement;
+ setScrollMetrics(scrollContainer, {
+ scrollTop: 50,
+ scrollHeight: 5000,
+ clientHeight: 800,
+ });
+
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+ loadOlder.mockClear();
+ fireEvent.scroll(scrollContainer);
+ expect(loadOlder).toHaveBeenCalledTimes(1);
+
+ vi.mocked(useConversationId).mockReturnValue({
+ conversationId: "next-conversation-id",
+ });
+ vi.mocked(useOptionalConversationId).mockReturnValue({
+ conversationId: "next-conversation-id",
+ });
+ view.rerender(renderChat());
+
+ const setScrollTop = vi.fn();
+ Object.defineProperty(scrollContainer, "scrollTop", {
+ configurable: true,
+ get: () => 0,
+ set: setScrollTop,
+ });
+ Object.defineProperty(scrollContainer, "scrollHeight", {
+ configurable: true,
+ value: 6000,
+ });
+
+ const nextConversationEvent: MessageEvent = {
+ id: "msg-next-conversation",
+ timestamp: "2025-07-02T00:00:00Z",
+ source: "user",
+ llm_message: {
+ role: "user",
+ content: [{ type: "text", text: "Next conversation message" }],
+ },
+ activated_skills: [],
+ extended_content: [],
+ };
+ act(() => {
+ useEventStore.getState().addEvent(nextConversationEvent);
+ });
+
+ // Restoring the previous conversation's geometry would assign
+ // prevTop + (newHeight - prevHeight) = 50 + (6000 - 5000) = 1050.
+ expect(setScrollTop).not.toHaveBeenCalledWith(1050);
+ });
+
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.
@@ -497,6 +565,7 @@ describe("ChatInterface - Scroll-up loads older events", () => {
events: [seedEvent],
eventIds: new Set(["msg-seed"]),
uiEvents: [seedEvent],
+ loadedConversationId: "test-conversation-id",
});
const useUserConversationModule =
diff --git a/__tests__/hooks/use-load-older-events.test.tsx b/__tests__/hooks/use-load-older-events.test.tsx
index 2fda08f230..ad92505965 100644
--- a/__tests__/hooks/use-load-older-events.test.tsx
+++ b/__tests__/hooks/use-load-older-events.test.tsx
@@ -50,6 +50,39 @@ function makeEvent(id: string, timestamp: string): OpenHandsEvent {
return { id, timestamp } as unknown as OpenHandsEvent;
}
+function makeUserMessage(id: string, timestamp: string): OpenHandsEvent {
+ return {
+ id,
+ timestamp,
+ source: "user",
+ llm_message: { role: "user", content: [{ type: "text", text: "hi" }] },
+ activated_skills: [],
+ extended_content: [],
+ } as unknown as OpenHandsEvent;
+}
+
+function makeModelSwitchObservation(
+ id: string,
+ timestamp: string,
+): OpenHandsEvent {
+ return {
+ id,
+ timestamp,
+ source: "environment",
+ action_id: `action-${id}`,
+ tool_name: "switch_llm",
+ tool_call_id: `call-${id}`,
+ observation: {
+ kind: "SwitchLLMObservation",
+ content: [{ type: "text", text: "Switched to fast-opus" }],
+ is_error: false,
+ profile_name: "fast-opus",
+ reason: null,
+ active_model: null,
+ },
+ } as unknown as OpenHandsEvent;
+}
+
function makePage(
items: OpenHandsEvent[],
nextPageId: string | null = null,
@@ -57,6 +90,17 @@ function makePage(
return { items, next_page_id: nextPageId };
}
+function makeDeferred<T>() {
+ let resolve!: (value: T | PromiseLike<T>) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+
+ return { promise, resolve, reject };
+}
+
describe("useLoadOlderEvents", () => {
let queryClient: QueryClient;
let wrapper: ({
@@ -65,6 +109,30 @@ describe("useLoadOlderEvents", () => {
children: React.ReactNode;
}) => React.ReactElement;
+ const setConversationEvents = (
+ conversationId: string,
+ events: OpenHandsEvent[] = [],
+ ) => {
+ act(() => {
+ useEventStore.getState().clearEventsForConversation(conversationId);
+ useEventStore.getState().addEvents(events);
+ });
+ };
+
+ const renderConversationHook = (conversationId: string) =>
+ renderHook(({ id }) => useLoadOlderEvents(id), {
+ initialProps: { id: conversationId },
+ wrapper,
+ });
+
+ const startLoad = (loadOlder: () => Promise<void>) => {
+ let load!: Promise<void>;
+ act(() => {
+ load = loadOlder();
+ });
+ return load;
+ };
+
beforeEach(() => {
queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -78,7 +146,7 @@ describe("useLoadOlderEvents", () => {
// Reset event store between tests so prior tests don't leak state.
act(() => {
- useEventStore.getState().clearEvents();
+ useEventStore.getState().clearEventsForConversation("conv-1");
useModelStore.getState().clearAll();
});
@@ -175,30 +243,11 @@ describe("useLoadOlderEvents", () => {
// Older page (server returns TIMESTAMP_DESC; the hook reverses it): a user
// message followed by the agent's successful model switch.
- const userMsg = {
- id: "evt-user-old",
- timestamp: "2024-05-01T00:00:00Z",
- source: "user",
- llm_message: { role: "user", content: [{ type: "text", text: "hi" }] },
- activated_skills: [],
- extended_content: [],
- } as unknown as OpenHandsEvent;
- const switchObs = {
- id: "evt-switch-old",
- timestamp: "2024-05-02T00:00:00Z",
- source: "environment",
- action_id: "action-switch-old",
- tool_name: "switch_llm",
- tool_call_id: "call-switch-old",
- observation: {
- kind: "SwitchLLMObservation",
- content: [{ type: "text", text: "Switched to fast-opus" }],
- is_error: false,
- profile_name: "fast-opus",
- reason: null,
- active_model: null,
- },
- } as unknown as OpenHandsEvent;
+ const userMsg = makeUserMessage("evt-user-old", "2024-05-01T00:00:00Z");
+ const switchObs = makeModelSwitchObservation(
+ "evt-switch-old",
+ "2024-05-02T00:00:00Z",
+ );
vi.spyOn(EventService, "searchEvents").mockResolvedValue(
// Descending order, as the server returns it.
@@ -265,16 +314,11 @@ describe("useLoadOlderEvents", () => {
.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 pendingPage = makeDeferred<EventSearchPage<OpenHandsEvent>>();
const spy = vi
.spyOn(EventService, "searchEvents")
- .mockReturnValue(pendingPage);
+ .mockReturnValue(pendingPage.promise);
const { result } = renderHook(() => useLoadOlderEvents("conv-1"), {
wrapper,
@@ -291,13 +335,166 @@ describe("useLoadOlderEvents", () => {
expect(result.current.isLoading).toBe(true);
await act(async () => {
- resolvePage(makePage([makeEvent("evt-older", "2024-05-01T00:00:00Z")], null));
+ pendingPage.resolve(
+ makePage([makeEvent("evt-older", "2024-05-01T00:00:00Z")], null),
+ );
await Promise.all([firstLoad, secondLoad]);
});
expect(result.current.isLoading).toBe(false);
});
+ it("discards an older-events page after switching conversations", async () => {
+ setConversationEvents("conv-a", [
+ makeEvent("evt-a-recent", "2024-06-01T00:00:00Z"),
+ ]);
+
+ const pendingPage = makeDeferred<EventSearchPage<OpenHandsEvent>>();
+ vi.spyOn(EventService, "searchEvents").mockReturnValue(pendingPage.promise);
+
+ const { result, rerender } = renderConversationHook("conv-a");
+ const load = startLoad(result.current.loadOlder);
+
+ rerender({ id: "conv-b" });
+ setConversationEvents("conv-b", [
+ makeEvent("evt-b-recent", "2024-07-01T00:00:00Z"),
+ ]);
+
+ await act(async () => {
+ pendingPage.resolve(
+ makePage([
+ makeModelSwitchObservation("evt-a-switch", "2024-05-02T00:00:00Z"),
+ makeUserMessage("evt-a-user", "2024-05-01T00:00:00Z"),
+ ]),
+ );
+ await load;
+ });
+
+ expect(useEventStore.getState().events.map((event) => event.id)).toEqual([
+ "evt-b-recent",
+ ]);
+ expect(result.current.hasMore).toBe(true);
+ expect(
+ useModelStore.getState().entriesByConversation["conv-a"],
+ ).toBeUndefined();
+ });
+
+ it("discards a stale page after switching away and back", async () => {
+ setConversationEvents("conv-a", [
+ makeEvent("evt-a-first-visit", "2024-06-01T00:00:00Z"),
+ ]);
+
+ const pendingPage = makeDeferred<EventSearchPage<OpenHandsEvent>>();
+ vi.spyOn(EventService, "searchEvents").mockReturnValue(pendingPage.promise);
+
+ const { result, rerender } = renderConversationHook("conv-a");
+ const load = startLoad(result.current.loadOlder);
+
+ rerender({ id: "conv-b" });
+ setConversationEvents("conv-b");
+ rerender({ id: "conv-a" });
+ setConversationEvents("conv-a", [
+ makeEvent("evt-a-second-visit", "2024-07-01T00:00:00Z"),
+ ]);
+
+ await act(async () => {
+ pendingPage.resolve(
+ makePage([makeEvent("evt-a-stale", "2024-05-01T00:00:00Z")]),
+ );
+ await load;
+ });
+
+ expect(useEventStore.getState().events.map((event) => event.id)).toEqual([
+ "evt-a-second-visit",
+ ]);
+ });
+
+ it("ignores a request failure after switching conversations", async () => {
+ setConversationEvents("conv-a", [
+ makeEvent("evt-a-recent", "2024-06-01T00:00:00Z"),
+ ]);
+
+ const pendingPage = makeDeferred<EventSearchPage<OpenHandsEvent>>();
+ vi.spyOn(EventService, "searchEvents").mockReturnValue(pendingPage.promise);
+
+ const { result, rerender } = renderConversationHook("conv-a");
+ const load = startLoad(result.current.loadOlder);
+
+ rerender({ id: "conv-b" });
+ setConversationEvents("conv-b");
+
+ await act(async () => {
+ pendingPage.reject(new Error("stale request failed"));
+ await load;
+ });
+
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it("does not let an older request clear a newer request's loading state", async () => {
+ setConversationEvents("conv-a", [
+ makeEvent("evt-a-recent", "2024-06-01T00:00:00Z"),
+ ]);
+
+ const pageA = makeDeferred<EventSearchPage<OpenHandsEvent>>();
+ const pageB = makeDeferred<EventSearchPage<OpenHandsEvent>>();
+ vi.spyOn(EventService, "searchEvents")
+ .mockReturnValueOnce(pageA.promise)
+ .mockReturnValueOnce(pageB.promise);
+
+ const { result, rerender } = renderConversationHook("conv-a");
+ const loadA = startLoad(result.current.loadOlder);
+
+ rerender({ id: "conv-b" });
+ setConversationEvents("conv-b", [
+ makeEvent("evt-b-recent", "2024-07-01T00:00:00Z"),
+ ]);
+
+ const loadB = startLoad(result.current.loadOlder);
+ expect(result.current.isLoading).toBe(true);
+
+ await act(async () => {
+ pageA.resolve(
+ makePage([makeEvent("evt-a-older", "2024-05-01T00:00:00Z")]),
+ );
+ await loadA;
+ });
+ expect(result.current.isLoading).toBe(true);
+
+ await act(async () => {
+ pageB.resolve(
+ makePage([makeEvent("evt-b-older", "2024-06-01T00:00:00Z")]),
+ );
+ await loadB;
+ });
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it("does not merge a pending page after the hook unmounts", async () => {
+ setConversationEvents("conv-1", [
+ makeEvent("evt-recent", "2024-06-01T00:00:00Z"),
+ ]);
+
+ const pendingPage = makeDeferred<EventSearchPage<OpenHandsEvent>>();
+ vi.spyOn(EventService, "searchEvents").mockReturnValue(pendingPage.promise);
+
+ const { result, unmount } = renderConversationHook("conv-1");
+ const load = startLoad(result.current.loadOlder);
+
+ unmount();
+
+ await act(async () => {
+ pendingPage.resolve(
+ makePage([makeEvent("evt-older", "2024-05-01T00:00:00Z")]),
+ );
+ await load;
+ });
+
+ expect(useEventStore.getState().events.map((event) => event.id)).toEqual([
+ "evt-recent",
+ ]);
+ });
+
it("cleans up loading state and rethrows when the page request fails", async () => {
act(() => {
useEventStore
diff --git a/src/components/features/chat/chat-interface.tsx b/src/components/features/chat/chat-interface.tsx
index ff6b46ccc4..12bb5a1bee 100644
--- a/src/components/features/chat/chat-interface.tsx
+++ b/src/components/features/chat/chat-interface.tsx
@@ -213,6 +213,14 @@ export function ChatInterface() {
scrollHeight: number;
scrollTop: number;
} | null>(null);
+
+ React.useEffect(() => {
+ // A pending history load may be discarded during a conversation switch.
+ // Do not let the previous conversation's saved scroll geometry affect the
+ // next conversation's scroll restoration.
+ preserveScrollPosition.current = null;
+ }, [conversationId]);
+
const maybeLoadOlder = React.useCallback(
(target: HTMLElement) => {
if (isProvisioningTask || isLoadingOlderEvents || !hasMoreOlderEvents) {
diff --git a/src/hooks/use-load-older-events.ts b/src/hooks/use-load-older-events.ts
index 1578d1efac..9f3e38a38a 100644
--- a/src/hooks/use-load-older-events.ts
+++ b/src/hooks/use-load-older-events.ts
@@ -22,7 +22,10 @@ interface UseLoadOlderEventsResult {
* 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. */
+ /**
+ * Trigger one more older-events page. Resolves after the page is merged, or
+ * without changing state if the load became stale.
+ */
loadOlder: () => Promise<void>;
}
@@ -54,6 +57,13 @@ export const useLoadOlderEvents = (
const [hasMore, setHasMore] = React.useState(true);
const isLoadingRef = React.useRef(false);
const hasMoreRef = React.useRef(true);
+ const activeLoadMarkerRef = React.useRef<object | null>(null);
+
+ React.useEffect(() => {
+ return () => {
+ activeLoadMarkerRef.current = null;
+ };
+ }, [conversationId]);
React.useEffect(() => {
isLoadingRef.current = false;
@@ -121,6 +131,12 @@ export const useLoadOlderEvents = (
isLoadingRef.current = true;
setIsLoading(true);
+ const loadMarker = {};
+ activeLoadMarkerRef.current = loadMarker;
+ const isActiveLoad = () =>
+ activeLoadMarkerRef.current === loadMarker &&
+ useEventStore.getState().loadedConversationId === conversationId;
+
try {
const page = await EventService.searchEvents(
conversationId,
@@ -133,6 +149,14 @@ export const useLoadOlderEvents = (
},
);
+ // Conversation switches atomically replace `loadedConversationId` and
+ // clear the global event store. Do not merge this page if the store now
+ // belongs to another conversation. There is no `await` below this guard,
+ // so a navigation cannot interleave between the check and `addEvents`.
+ if (!isActiveLoad()) {
+ return;
+ }
+
if (!Array.isArray(page.items)) {
throw new Error(
"Invalid older-events response: expected page.items to be an array.",
@@ -159,9 +183,20 @@ export const useLoadOlderEvents = (
hasMoreRef.current = false;
setHasMore(false);
}
+ } catch (error) {
+ // Errors from an abandoned conversation are no longer relevant to the
+ // active view. Preserve the existing error behavior for current loads.
+ if (isActiveLoad()) {
+ throw error;
+ }
} finally {
- isLoadingRef.current = false;
- setIsLoading(false);
+ // A newer conversation may already have its own request in flight; an
+ // older request must not clear that request's loading state.
+ if (isActiveLoad()) {
+ activeLoadMarkerRef.current = null;
+ isLoadingRef.current = false;
+ setIsLoading(false);
+ }
}
}, [
conversationId,