π OpenHands: AI-Driven Development
fix(conversation): keep the first Cloud message when the history page lags the runtime (#18719)
Engel Nyst1ce086d3fca1
diff --git a/.pr/cloud-first-message-cursor/README.md b/.pr/cloud-first-message-cursor/README.mdnew file mode 100644index 0000000000..492274ca30--- /dev/null+++ b/.pr/cloud-first-message-cursor/README.md@@ -0,0 +1,80 @@+# Cloud first message: history cursor (#18717)++Evidence for the fix in `src/hooks/query/use-conversation-history.ts`.++## Before (from the issue, main@1f7b1e69a)++The socket opened with `after_seq=5`, taken from the runtime's event count,+while the history page came from the Cloud App API. The user `MessageEvent` was+runtime seq 3 and was missing from that page, so neither path delivered it. The+bubble stayed "Sending..." below the reply and became "Failed to send" after+150 s:++- https://raw.githubusercontent.com/OpenHands/OpenHands/68d71905b219fdb2795da2c19604e7bf0a832cd3/.pr/bugs/2026-10-20/cloud-first-message-pending/sending-below-reply.png+- https://raw.githubusercontent.com/OpenHands/OpenHands/68d71905b219fdb2795da2c19604e7bf0a832cd3/.pr/bugs/2026-10-20/cloud-first-message-pending/failed-to-send-before-reload.png++## After (this branch, real OpenHands Cloud backend)++Harness: `control-openhands launch --new --print-run --timeout 900` built this+worktree, then `onboard --skip`. The Cloud backend was added with Add Backend β+Cloud β Authorize Device (recipe F25 "Cloud backend"). The first message was+sent from Home:++```sh+control-openhands browser fill 'testid=chat-input' 'Reply with exactly: QA_CLOUD_FIX. Do not run any tools.'+control-openhands browser click 'testid=submit-button' --expect-url '/conversations/'+# at ~30 s, ~90 s and ~165 s:+control-openhands browser eval "<message rows in testid=chat-scroll-container, Sending.../Failed to send flags>"+control-openhands browser events --kinds websocket-created --last 5+```++| Time after send | Message rows (in order) | Sending... | Failed to send | Socket |+| --- | --- | --- | --- | --- |+| 30 s | user-message, pending (sandbox still starting, socket not open yet) | yes | no | none yet |+| 38 s | user-message, agent-message `QA_CLOUD_FIX`, 2 hook rows | no | no | `/sockets/session/<id>?after_seq=-1` |+| 92 s | user-message, agent-message, 2 hook rows | no | no | same, no reconnect |+| 167 s (past the 150 s watchdog) | user-message, agent-message, 2 hook rows | no | no | same, no reconnect |+| after a reload | user-message, agent-message, 2 hook rows | no | no | `after_seq=-1` again |++There was exactly one `user-message` and one `agent-message` at every point,+including after the reload, so the replay added no duplicate rows. The page+shows the same order as before the reload.++Screenshots of the chat panel only. The sidebar is cropped out because it lists+the Cloud account's other conversations.++- `cloud-after-40s.png`: the user message first, then the reply, with nothing pending.+- `cloud-after-165s.png`: the same after the 150 s watchdog, still with no "Failed to send".++### Replay deduplication: event ids are shared between the two logs++For the same conversation, comparing `GET /api/v1/conversation/<id>/events/search`+(App API) with the runtime's `GET <conversation_url>/events/search`:++- App API: 10 events. Runtime: 11 events (`/events/count` = 11).+- 9 event ids are identical in both. Only in the App API:+ 1 `ConversationStateUpdateEvent`. Only in the runtime: 2 `HookExecutionEvent`s,+ which the App API page still lacked.++The events that both logs hold have the same id, so the event store's id dedupe+absorbs the replayed overlap. The runtime-only hook rows reach the page through+the replay.++### Local backend unchanged++On the same run (`control-openhands llm preset deepseek`), I started a local+conversation from Home with `Reply with exactly: QA_LOCAL_FIX. Do not run any+tools.`. It showed user-message, then agent-message `QA_LOCAL_FIX`, with no+pending state and no duplicates. The socket still resumes at the count's tail:+`after_seq=3` on the first connect, and `after_seq=6` after a reload with+`/events/count` = 7. Screenshot: `local-after.png`.++### Cloud cleanup++I deleted the Cloud conversation through the UI (`conversation-name >>+ellipsis-button`, `delete-button`, confirm). The App API then returned `[null]`+for its id, and the account's conversation list matched the list from before+the run. I removed the Cloud backend in Manage Backends, and the selector read+`Local` again. I deleted the device grant's API key `Device Link Access Key+(<code of this run>)` with `DELETE /api/keys/<id>` and left every other key in+place.diff --git a/.pr/cloud-first-message-cursor/cloud-after-165s.png b/.pr/cloud-first-message-cursor/cloud-after-165s.pngnew file mode 100644index 0000000000..73720d6775Binary files /dev/null and b/.pr/cloud-first-message-cursor/cloud-after-165s.png differdiff --git a/.pr/cloud-first-message-cursor/cloud-after-40s.png b/.pr/cloud-first-message-cursor/cloud-after-40s.pngnew file mode 100644index 0000000000..73720d6775Binary files /dev/null and b/.pr/cloud-first-message-cursor/cloud-after-40s.png differdiff --git a/.pr/cloud-first-message-cursor/local-after.png b/.pr/cloud-first-message-cursor/local-after.pngnew file mode 100644index 0000000000..d5209a9e13Binary files /dev/null and b/.pr/cloud-first-message-cursor/local-after.png differdiff --git a/__tests__/hooks/query/use-conversation-history.test.tsx b/__tests__/hooks/query/use-conversation-history.test.tsxindex 1806e22b40..34978bb139 100644--- a/__tests__/hooks/query/use-conversation-history.test.tsx+++ b/__tests__/hooks/query/use-conversation-history.test.tsx@@ -12,6 +12,11 @@ import {useConversationHistory,} from "#/hooks/query/use-conversation-history";import EventService from "#/api/event-service/event-service.api";+import {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";import { useUserConversation } from "#/hooks/query/use-user-conversation";import type { Conversation } from "#/api/open-hands.types";import type { OpenHandsEvent } from "#/types/agent-server/core";@@ -516,5 +521,74 @@ describe("useConversationHistory cache key stability", () => {expect(result.current.data?.events).toHaveLength(1);expect(result.current.data?.afterSeq).toBeNull();});++ describe("on a Cloud backend", () => {+ // The count is the runtime's log, but the page comes from the App+ // API's webhook-fed copy of it, which can lag the runtime.+ beforeEach(() => {+ setRegisteredBackends([+ {+ id: "cloud-1",+ name: "OpenHands Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "k",+ kind: "cloud",+ },+ ]);+ setActiveSelection({ backendId: "cloud-1" });+ });++ afterEach(() => {+ window.localStorage.clear();+ __resetActiveStoreForTests();+ });++ it("does not resume past runtime events the lagging page lacks", async () => {+ // Arrange: the runtime holds 6 events (seq 0..5) and the user's+ // first message is seq 3, but the App API page has only seq 0..2.+ withUrl();+ vi.spyOn(EventService, "getEventCount").mockResolvedValue(6);+ vi.spyOn(EventService, "searchEvents").mockResolvedValue(+ makePage([+ makeEvent("evt-2"),+ makeEvent("evt-1"),+ makeEvent("evt-0"),+ ]),+ );++ // Act+ const { result } = renderHook(+ () => useConversationHistory("conv-cloud-lag"),+ { wrapper },+ );+ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ // Assert: the socket replays the whole short log (deduped by id)+ // instead of resuming after seq 5 and losing the message.+ expect(result.current.data?.afterSeq).toBe(-1);+ });++ it("replays only one page-width of a long runtime log", async () => {+ // Arrange+ withUrl();+ vi.spyOn(EventService, "getEventCount").mockResolvedValue(120);+ vi.spyOn(EventService, "searchEvents").mockResolvedValue(+ makePage([makeEvent()]),+ );++ // Act+ const { result } = renderHook(+ () => useConversationHistory("conv-cloud-long"),+ { wrapper },+ );+ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ // Assert: the newest INITIAL_HISTORY_PAGE_SIZE runtime events are+ // replayed, not the whole log.+ expect(result.current.data?.afterSeq).toBe(+ 119 - INITIAL_HISTORY_PAGE_SIZE,+ );+ });+ });});});diff --git a/src/hooks/query/use-conversation-history.ts b/src/hooks/query/use-conversation-history.tsindex f308c39f60..41ce540e59 100644--- a/src/hooks/query/use-conversation-history.ts+++ b/src/hooks/query/use-conversation-history.ts@@ -1,5 +1,6 @@import { useQuery } from "@tanstack/react-query";import EventService from "#/api/event-service/event-service.api";+import { getActiveBackend } from "#/api/backend-registry/active-store";import { useUserConversation } from "#/hooks/query/use-user-conversation";import type { OpenHandsEvent } from "#/types/agent-server/core";@@ -19,12 +20,33 @@ export interface ConversationHistoryPage {/*** Session-socket resume cursor for the first connect: the last `seq` on* disk *before* this page was read, so nothing appended in between is- * missed and nothing older than the page is replayed. `null` when the count+ * missed and nothing older than the page is replayed. On Cloud it is one+ * page-width further back (see `resumeCursor`). `null` when the count* could not be read.*/afterSeq: number | null;}+/**+ * First-connect `after_seq` from the runtime's event count.+ *+ * Locally the count and the page are the same log, so the socket resumes at+ * the count's tail. On Cloud the page comes from the App API's webhook-fed+ * copy of the log (`EventService.searchEvents`), which can lag the runtime:+ * resuming at the runtime's tail would skip every event the page does not yet+ * hold β the first user message's echo among them (#18717). There the socket+ * replays the newest page-width of the runtime log instead; the event store+ * dedupes what the page already has by id (both logs share event ids). Only+ * a lag of more than a page could still leave a hole; the whole log is not+ * replayed because that would load every older event of a long conversation+ * past pagination and re-run their socket side effects.+ */+function resumeCursor(count: number): number {+ const lastSeq = count - 1;+ if (getActiveBackend().backend.kind !== "cloud") return lastSeq;+ return Math.max(-1, lastSeq - INITIAL_HISTORY_PAGE_SIZE);+}+/*** 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;@@ -93,7 +115,7 @@ export const useConversationHistory = (conversationId?: string) => {hasMore:!!page.next_page_id || page.items.length >= INITIAL_HISTORY_PAGE_SIZE,nextPageId: page.next_page_id ?? null,- afterSeq: typeof count === "number" ? count - 1 : null,+ afterSeq: typeof count === "number" ? resumeCursor(count) : null,};},// Keep the cached page so returning to a conversation renders the