π OpenHands: AI-Driven Development
feat(canvas): retire streaming slots by event id and delete the text-matching reconciler (#17465)
Vasco Schiavo1ec86616bc05
diff --git a/__tests__/api/agent-server-adapter.test.ts b/__tests__/api/agent-server-adapter.test.tsindex 10d6825a57..4cb05ed830 100644--- a/__tests__/api/agent-server-adapter.test.ts+++ b/__tests__/api/agent-server-adapter.test.ts@@ -1427,7 +1427,7 @@ describe("buildRuntimeServicesSystemSuffix", () => {it("fetches runtime services from cached server_info when available", async () => {mockGetCachedAgentServerInfo.mockReturnValue({- version: "1.28.0",+ version: "1.48.0",runtime_services: {mode: "docker",services: {@@ -1452,7 +1452,7 @@ describe("buildRuntimeServicesSystemSuffix", () => {it("fetches runtime services from /server_info when there is no cached probe", async () => {mockGetServerInfo.mockResolvedValue({- version: "1.28.0",+ version: "1.48.0",runtime_services: {mode: "dev:automation",services: {diff --git a/__tests__/api/mock-settings-catalog.test.ts b/__tests__/api/mock-settings-catalog.test.tsindex 084e4e2af1..e0e1a95edc 100644--- a/__tests__/api/mock-settings-catalog.test.ts+++ b/__tests__/api/mock-settings-catalog.test.ts@@ -72,7 +72,7 @@ describe("mock agent-server discovery", () => {security_analyzers: string[];}>("/server_info");expect(serverInfo).toMatchObject({- version: "1.36.1",+ version: "1.48.0",usable_tools: ["terminal","file_editor",diff --git a/__tests__/build-websocket-url.test.ts b/__tests__/build-websocket-url.test.tsindex 41c30fe851..51749776b5 100644--- a/__tests__/build-websocket-url.test.ts+++ b/__tests__/build-websocket-url.test.ts@@ -18,7 +18,7 @@ describe("buildWebSocketUrl", () => {"http://localhost:8080/api/conversations/conv-123",);- expect(result).toBe("ws://localhost:8080/sockets/events/conv-123");+ expect(result).toBe("ws://localhost:8080/sockets/session/conv-123");});it("should use wss:// protocol when window.location.protocol is https:", () => {@@ -32,7 +32,7 @@ describe("buildWebSocketUrl", () => {"https://example.com:8080/api/conversations/conv-123",);- expect(result).toBe("wss://example.com:8080/sockets/events/conv-123");+ expect(result).toBe("wss://example.com:8080/sockets/session/conv-123");});it("should use ws:// for external HTTP hosts when page is HTTP", () => {@@ -46,7 +46,7 @@ describe("buildWebSocketUrl", () => {"http://agent-server.com:9000/api/conversations/conv-456",);- expect(result).toBe("ws://agent-server.com:9000/sockets/events/conv-456");+ expect(result).toBe("ws://agent-server.com:9000/sockets/session/conv-456");});it("should use wss:// for external HTTPS hosts when page is HTTP", () => {@@ -61,7 +61,7 @@ describe("buildWebSocketUrl", () => {);expect(result).toBe(- "wss://agent-server.com:9000/sockets/events/conv-456",+ "wss://agent-server.com:9000/sockets/session/conv-456",);});@@ -76,7 +76,7 @@ describe("buildWebSocketUrl", () => {"http://127.0.0.1:9000/api/conversations/conv-456",);- expect(result).toBe("ws://127.0.0.1:9000/sockets/events/conv-456");+ expect(result).toBe("ws://127.0.0.1:9000/sockets/session/conv-456");});});@@ -94,7 +94,7 @@ describe("buildWebSocketUrl", () => {"http://localhost:8080/api/conversations/conv-123",);- expect(result).toBe("ws://localhost:8080/sockets/events/conv-123");+ expect(result).toBe("ws://localhost:8080/sockets/session/conv-123");expect(result).not.toContain("?");expect(result).not.toContain("session_api_key");});@@ -109,7 +109,7 @@ describe("buildWebSocketUrl", () => {const result = buildWebSocketUrl("conv-123", null);- expect(result).toBe("ws://fallback-host:4000/sockets/events/conv-123");+ expect(result).toBe("ws://fallback-host:4000/sockets/session/conv-123");});it("should use window.location.host when conversation URL is undefined", () => {@@ -120,7 +120,7 @@ describe("buildWebSocketUrl", () => {const result = buildWebSocketUrl("conv-123", undefined);- expect(result).toBe("ws://fallback-host:4000/sockets/events/conv-123");+ expect(result).toBe("ws://fallback-host:4000/sockets/session/conv-123");});it("should use window.location.host when conversation URL is relative path", () => {@@ -134,7 +134,7 @@ describe("buildWebSocketUrl", () => {"/api/conversations/conv-123",);- expect(result).toBe("ws://fallback-host:4000/sockets/events/conv-123");+ expect(result).toBe("ws://fallback-host:4000/sockets/session/conv-123");});it("should use window.location.host when conversation URL is invalid", () => {@@ -145,7 +145,7 @@ describe("buildWebSocketUrl", () => {const result = buildWebSocketUrl("conv-123", "not-a-valid-url");- expect(result).toBe("ws://fallback-host:4000/sockets/events/conv-123");+ expect(result).toBe("ws://fallback-host:4000/sockets/session/conv-123");});});@@ -181,7 +181,7 @@ describe("buildWebSocketUrl", () => {"http://example.com:12345/api/conversations/conv-123",);- expect(result).toBe("ws://example.com:12345/sockets/events/conv-123");+ expect(result).toBe("ws://example.com:12345/sockets/session/conv-123");});it("should handle conversation URLs without port (default port) on external hosts", () => {@@ -190,7 +190,7 @@ describe("buildWebSocketUrl", () => {"http://example.com/api/conversations/conv-123",);- expect(result).toBe("ws://example.com/sockets/events/conv-123");+ expect(result).toBe("ws://example.com/sockets/session/conv-123");});it("should handle conversation IDs with special characters", () => {@@ -200,7 +200,7 @@ describe("buildWebSocketUrl", () => {);expect(result).toBe(- "ws://localhost:8080/sockets/events/conv-123-abc_def",+ "ws://localhost:8080/sockets/session/conv-123-abc_def",);});@@ -210,7 +210,7 @@ describe("buildWebSocketUrl", () => {"http://localhost:8080/api/conversations/conv-123",);- expect(result).toBe("ws://localhost:8080/sockets/events/conv-123");+ expect(result).toBe("ws://localhost:8080/sockets/session/conv-123");expect(result).not.toContain("?");});});@@ -232,7 +232,7 @@ describe("buildWebSocketUrl", () => {);expect(result).toBe(- `wss://${fakeRuntimeHost}/sockets/events/${fakeConversationId}`,+ `wss://${fakeRuntimeHost}/sockets/session/${fakeConversationId}`,);});@@ -247,7 +247,7 @@ describe("buildWebSocketUrl", () => {"http://[::1]:8080/api/conversations/test-conv-ipv6",);- expect(result).toBe("ws://[::1]:8080/sockets/events/test-conv-ipv6");+ expect(result).toBe("ws://[::1]:8080/sockets/session/test-conv-ipv6");});it("should use ws:// for .localhost subdomains", () => {@@ -262,7 +262,7 @@ describe("buildWebSocketUrl", () => {);expect(result).toBe(- "ws://api.localhost:8080/sockets/events/test-conv-localhost-subdomain",+ "ws://api.localhost:8080/sockets/session/test-conv-localhost-subdomain",);});});diff --git a/__tests__/components/backends/add-backend-modal.test.tsx b/__tests__/components/backends/add-backend-modal.test.tsxindex ad56c83882..af6fdc98b2 100644--- a/__tests__/components/backends/add-backend-modal.test.tsx+++ b/__tests__/components/backends/add-backend-modal.test.tsx@@ -83,7 +83,7 @@ beforeEach(() => {captureMock = vi.spyOn(telemetry, "trackEvent").mockResolvedValue(undefined);window.localStorage.clear();getServerInfoMock.mockReset();- getServerInfoMock.mockResolvedValue({ version: "1.28.0" });+ getServerInfoMock.mockResolvedValue({ version: "1.48.0" });deviceFlowMocks.startDeviceFlow.mockReset();deviceFlowMocks.startDeviceFlow.mockResolvedValue({device_code: "device-code",@@ -413,7 +413,7 @@ describe("AddBackendModal β connection chooser", () => {await user.click(screen.getByTestId("add-backend-submit"));expect(await screen.findByTestId("add-backend-error")).toHaveTextContent(- "Agent Canvas requires agent-server 1.28.0 or newer",+ "Agent Canvas requires agent-server 1.47.0 or newer",);expect(onClose).not.toHaveBeenCalled();});diff --git a/__tests__/components/backends/api-key-entry-screen.test.tsx b/__tests__/components/backends/api-key-entry-screen.test.tsxindex 110a930bbd..3544d1525d 100644--- a/__tests__/components/backends/api-key-entry-screen.test.tsx+++ b/__tests__/components/backends/api-key-entry-screen.test.tsx@@ -18,7 +18,7 @@ vi.mock("@openhands/typescript-client/clients", () => ({}),// ServerClient needed by useBackendsHealth (imported transitively)ServerClient: vi.fn(function ServerClientMock() {- return { getServerInfo: vi.fn().mockResolvedValue({ version: "1.28.0" }) };+ return { getServerInfo: vi.fn().mockResolvedValue({ version: "1.48.0" }) };}),}));diff --git a/__tests__/components/backends/backend-form-modal.test.tsx b/__tests__/components/backends/backend-form-modal.test.tsxindex 04c7cd0a39..5e72d244c3 100644--- a/__tests__/components/backends/backend-form-modal.test.tsx+++ b/__tests__/components/backends/backend-form-modal.test.tsx@@ -69,7 +69,7 @@ function TestSeed({beforeEach(() => {window.localStorage.clear();getServerInfoMock.mockReset();- getServerInfoMock.mockResolvedValue({ version: "1.28.0" });+ getServerInfoMock.mockResolvedValue({ version: "1.48.0" });__resetActiveStoreForTests();});diff --git a/__tests__/components/backends/backend-selector.test.tsx b/__tests__/components/backends/backend-selector.test.tsxindex 365687f11f..aa1976d9a8 100644--- a/__tests__/components/backends/backend-selector.test.tsx+++ b/__tests__/components/backends/backend-selector.test.tsx@@ -151,7 +151,7 @@ beforeEach(() => {vi.mocked(ServerClient).mockReset();vi.mocked(ServerClient).mockImplementation(function ServerClientMock() {return {- getServerInfo: vi.fn().mockResolvedValue({ version: "1.28.0" }),+ getServerInfo: vi.fn().mockResolvedValue({ version: "1.48.0" }),} as unknown as ServerClient;});vi.mocked(SettingsClient).mockReset();diff --git a/__tests__/components/backends/manage-backends-modal.test.tsx b/__tests__/components/backends/manage-backends-modal.test.tsxindex a6beea6e90..34b9033316 100644--- a/__tests__/components/backends/manage-backends-modal.test.tsx+++ b/__tests__/components/backends/manage-backends-modal.test.tsx@@ -32,7 +32,7 @@ const deviceFlowMocks = vi.hoisted(() => ({pollForToken: vi.fn(),}));-const getServerInfoMock = vi.fn().mockResolvedValue({ version: "1.28.0" });+const getServerInfoMock = vi.fn().mockResolvedValue({ version: "1.48.0" });const getSettingsMock = vi.fn().mockResolvedValue({});vi.mock("@openhands/typescript-client/clients", () => ({@@ -102,7 +102,7 @@ beforeEach(() => {vi.spyOn(telemetry, "isTelemetryEnabled").mockReturnValue(true);window.localStorage.clear();getServerInfoMock.mockReset();- getServerInfoMock.mockResolvedValue({ version: "1.28.0" });+ getServerInfoMock.mockResolvedValue({ version: "1.48.0" });getSettingsMock.mockReset();getSettingsMock.mockResolvedValue({});vi.mocked(getCloudOrganizations).mockReset();@@ -198,7 +198,7 @@ describe("ManageBackendsModal", () => {);expect(screen.getByTestId("manage-backends-status-detail-Local"),- ).toHaveTextContent("Agent Canvas requires agent-server 1.28.0 or newer");+ ).toHaveTextContent("Agent Canvas requires agent-server 1.47.0 or newer");});it("closes when the header close button is clicked", async () => {diff --git a/__tests__/components/conversation-events/chat/duplicate-streamed-message.test.tsx b/__tests__/components/conversation-events/chat/duplicate-streamed-message.test.tsxindex a9c27f8d57..e09460b3fc 100644--- a/__tests__/components/conversation-events/chat/duplicate-streamed-message.test.tsx+++ b/__tests__/components/conversation-events/chat/duplicate-streamed-message.test.tsx@@ -8,17 +8,20 @@ import {OpenHandsEvent,SecurityRisk,} from "#/types/agent-server/core";-import { StreamingDeltaEvent } from "#/types/agent-server/core/events/streaming-delta-event";-import { handleEventForUI } from "#/utils/handle-event-for-ui";+import {+ appendStreamingDeltas,+ handleEventForUI,+ openStreamingSlot,+} from "#/utils/handle-event-for-ui";import { Messages } from "#/components/conversation-events/chat/messages";// Regression for issue #1534. With stream=true the agent streams its-// pre-tool-call text as a StreamingDeltaEvent and then emits an intermediate-// ActionEvent whose `thought` is that same text. The chat hoists the action's-// thought into its own message, so the leftover streaming delta used to render-// the identical text a second time. This test drives the real reducer-// (handleEventForUI) and renders the real <Messages> tree to assert the text-// shows exactly once.+// pre-tool-call text into a slot and then emits the intermediate ActionEvent+// whose `thought` is that same text β built with the slot's own id, because+// the SDK mints it when the stream opens. The chat hoists the action's thought+// into its own message, so the slot must be retired rather than left to render+// the identical text a second time. These tests drive the real reducers and+// render the real <Messages> tree to assert the text shows exactly once.const THOUGHT ="I'll create a webpage explaining what OpenHands can do. " +@@ -39,17 +42,6 @@ const userMessage: MessageEvent = {extended_content: [],};-// The reasoning streamed as a delta; many models carry reasoning ONLY here, so-// the collapsible "Thinking" must survive the reconciliation.-const streamingDelta: StreamingDeltaEvent = {- id: "delta-1",- kind: "StreamingDeltaEvent",- timestamp: "2026-06-12T12:00:01Z",- source: "agent",- content: THOUGHT,- reasoning_content: "Considering the request before acting.",-};-const action: ActionEvent = {id: "action-1",timestamp: "2026-06-12T12:00:02Z",@@ -101,54 +93,110 @@ const observation: ObservationEvent = {action_id: "action-1",};-const reduce = (events: OpenHandsEvent[]): OpenHandsEvent[] =>- events.reduce<OpenHandsEvent[]>((ui, ev) => handleEventForUI(ev, ui), []);+/**+ * Replay a turn: `stream(itemId, β¦)` opens a slot and feeds it, everything+ * else goes through the durable reducer β the same order the session socket+ * delivers them in.+ */+const stream = (+ itemId: string,+ text: string | null,+ reasoning: string | null = null,+) => ({ itemId, text, reasoning });++type Step = OpenHandsEvent | ReturnType<typeof stream>;++const isStreamStep = (step: Step): step is ReturnType<typeof stream> =>+ "itemId" in step;++/** The durable events of a replay, in arrival order (the `allEvents` list). */+const durableOf = (steps: Step[]): OpenHandsEvent[] =>+ steps.filter((step): step is OpenHandsEvent => !isStreamStep(step));++const replay = (steps: Step[]): OpenHandsEvent[] =>+ steps.reduce<OpenHandsEvent[]>((ui, step) => {+ if (!isStreamStep(step)) {+ return handleEventForUI(step, ui);+ }+ const opened = openStreamingSlot(+ { type: "item_started", item_id: step.itemId },+ ui,+ );+ return appendStreamingDeltas(+ [+ ...(step.reasoning+ ? [+ {+ type: "delta" as const,+ item_id: step.itemId,+ attempt: 1,+ order: 0,+ kind: "reasoning" as const,+ content: step.reasoning,+ },+ ]+ : []),+ ...(step.text+ ? [+ {+ type: "delta" as const,+ item_id: step.itemId,+ attempt: 1,+ order: 1,+ kind: "text" as const,+ content: step.text,+ },+ ]+ : []),+ ],+ opened,+ );+ }, []);describe("issue #1534 β streamed intermediate message duplication", () => {it("renders the intermediate thought text exactly once", () => {- const allEvents = [userMessage, streamingDelta, action, observation];- const uiEvents = reduce(allEvents);+ const steps: Step[] = [+ userMessage,+ stream(action.id, THOUGHT, "Considering the request before acting."),+ action,+ observation,+ ];+ const uiEvents = replay(steps);const { container } = renderWithProviders(- <Messages messages={uiEvents} allEvents={allEvents} />,+ <Messages messages={uiEvents} allEvents={durableOf(steps)} />,);expect(countOccurrences(container.textContent ?? "", THOUGHT)).toBe(1);});- it("keeps the streamed reasoning visible (Thinking section survives)", () => {- const allEvents = [userMessage, streamingDelta, action, observation];- const uiEvents = reduce(allEvents);-- renderWithProviders(<Messages messages={uiEvents} allEvents={allEvents} />);+ it("retires the slot on the action that carries its id", () => {+ const streamed = replay([userMessage, stream(action.id, THOUGHT)]);+ // While streaming, the slot renders the provisional text.+ expect(streamed.map((event) => event.id)).toEqual([+ userMessage.id,+ action.id,+ ]);- // The collapsible "Thinking" section is still rendered (collapsed by- // default); expanding it reveals the reasoning that was streamed on the- // delta, proving the reconciliation kept the reasoning.- fireEvent.click(screen.getByTestId("collapsible-thinking-toggle"));- expect(- screen.getByTestId("collapsible-thinking-content").textContent ?? "",- ).toContain("Considering the request before acting.");+ const uiEvents = handleEventForUI(action, streamed);+ expect(uiEvents).toEqual([userMessage, action]);});it("renders a single Thinking section when the action carries its own reasoning", () => {- // When the finalized action also reports reasoning, the streamed delta's- // reasoning would duplicate the action's "Thinking" β so the delta is- // dropped and only one Thinking section renders.const reasoningAction: ActionEvent = {...action,reasoning_content: "Considering the request before acting.",};- const allEvents = [+ const steps: Step[] = [userMessage,- streamingDelta,+ stream(action.id, THOUGHT, "Considering the request before acting."),reasoningAction,observation,];- const uiEvents = reduce(allEvents);+ const uiEvents = replay(steps);const { container } = renderWithProviders(- <Messages messages={uiEvents} allEvents={allEvents} />,+ <Messages messages={uiEvents} allEvents={durableOf(steps)} />,);expect(screen.getAllByTestId("collapsible-thinking")).toHaveLength(1);@@ -172,69 +220,87 @@ describe("issue #1534 β streamed intermediate message duplication", () => {metadata: null,},};- const allEvents = [userMessage, streamingDelta, finalMessage];- const uiEvents = reduce(allEvents);+ const steps: Step[] = [+ userMessage,+ stream(finalMessage.id, THOUGHT),+ finalMessage,+ ];+ const uiEvents = replay(steps);expect(uiEvents.at(-1)).toBe(finalMessage);const { container } = renderWithProviders(- <Messages messages={uiEvents} allEvents={allEvents} />,+ <Messages messages={uiEvents} allEvents={durableOf(steps)} />,);expect(countOccurrences(container.textContent ?? "", THOUGHT)).toBe(1);expect(screen.getByLabelText("Score: 72.0%")).toBeInTheDocument();+ });++ it("keeps the streamed reasoning visible while the slot is still open", () => {+ const steps: Step[] = [+ userMessage,+ stream(action.id, THOUGHT, "Considering the request before acting."),+ ];+ const uiEvents = replay(steps);++ renderWithProviders(+ <Messages messages={uiEvents} allEvents={durableOf(steps)} />,+ );+fireEvent.click(screen.getByTestId("collapsible-thinking-toggle"));expect(- screen.getByTestId("collapsible-thinking-content"),- ).toHaveTextContent("Considering the request before acting.");+ screen.getByTestId("collapsible-thinking-content").textContent ?? "",+ ).toContain("Considering the request before acting.");});+});- it("renders once when streamed text has leading whitespace", () => {- const leadingWhitespaceDelta: StreamingDeltaEvent = {- ...streamingDelta,- content: `\n${THOUGHT}`,- };- const finalMessage: MessageEvent = {- id: "agent-msg-leading-whitespace",- timestamp: "2026-06-12T12:00:02Z",- source: "agent",- llm_message: {- role: "assistant",- content: [{ type: "text", text: THOUGHT }],- },- activated_skills: [],- extended_content: [],- };- const allEvents = [userMessage, leadingWhitespaceDelta, finalMessage];- const uiEvents = reduce(allEvents);+describe("reasoning on a finished message", () => {+ const REASONING = "I should inspect the files before replying to the user.";+ // Shape recorded from agent-server 1.47.0: the durable MessageEvent carries+ // the streamed reasoning on `llm_message.reasoning_content`.+ const finalMessage: MessageEvent = {+ id: "agent-reasoned",+ timestamp: "2026-06-12T12:00:02Z",+ source: "agent",+ llm_message: {+ role: "assistant",+ content: [{ type: "text", text: "All done." }],+ reasoning_content: REASONING,+ },+ activated_skills: [],+ extended_content: [],+ };++ it("keeps the Thinking section when the message retires its slot", () => {+ const steps: Step[] = [+ userMessage,+ stream(finalMessage.id, "All done.", REASONING),+ finalMessage,+ ];+ const uiEvents = replay(steps);expect(uiEvents.at(-1)).toBe(finalMessage);- const { container } = renderWithProviders(- <Messages messages={uiEvents} allEvents={allEvents} />,+ renderWithProviders(+ <Messages messages={uiEvents} allEvents={durableOf(steps)} />,);- expect(countOccurrences(container.textContent ?? "", THOUGHT)).toBe(1);+ expect(screen.getAllByTestId("collapsible-thinking")).toHaveLength(1);+ fireEvent.click(screen.getByTestId("collapsible-thinking-toggle"));+ expect(+ screen.getByTestId("collapsible-thinking-content"),+ ).toHaveTextContent(REASONING);});});-// A model that streams its reasoning but whose action `thought` does not repeat-// that text used to render the delta's reasoning and the action's own reasoning-// as two identical "Thinking" bubbles.+// A model that streams reasoning only: the slot renders it until the durable+// action β which carries the same reasoning, and the slot's id β replaces it.describe("duplicate Thinking blocks", () => {const REASONING ="Let me read the full PRD to understand all the requirements. " +"I need to see sections that were clipped.";- const reasoningOnlyDelta: StreamingDeltaEvent = {- id: "delta-reasoning-only",- kind: "StreamingDeltaEvent",- timestamp: "2026-06-12T12:00:01Z",- source: "agent",- content: null,- reasoning_content: REASONING,- };-const reasoningAction: ActionEvent = {...action,thought: [],@@ -242,16 +308,16 @@ describe("duplicate Thinking blocks", () => {};it("renders the reasoning in a single Thinking section", () => {- const allEvents = [+ const steps: Step[] = [userMessage,- reasoningOnlyDelta,+ stream(reasoningAction.id, null, REASONING),reasoningAction,observation,];- const uiEvents = reduce(allEvents);+ const uiEvents = replay(steps);const { container } = renderWithProviders(- <Messages messages={uiEvents} allEvents={allEvents} />,+ <Messages messages={uiEvents} allEvents={durableOf(steps)} />,);expect(screen.getAllByTestId("collapsible-thinking")).toHaveLength(1);@@ -263,19 +329,17 @@ describe("duplicate Thinking blocks", () => {expect(countOccurrences(container.textContent ?? "", REASONING)).toBe(1);});- it("keeps the streamed reasoning when the action carries none", () => {- const plainAction: ActionEvent = { ...action, thought: [] };- const allEvents = [+ it("renders the streamed reasoning while the slot is open", () => {+ const steps: Step[] = [userMessage,- reasoningOnlyDelta,- plainAction,- observation,+ stream(reasoningAction.id, null, REASONING),];- const uiEvents = reduce(allEvents);+ const uiEvents = replay(steps);- renderWithProviders(<Messages messages={uiEvents} allEvents={allEvents} />);+ renderWithProviders(+ <Messages messages={uiEvents} allEvents={durableOf(steps)} />,+ );- // The delta is the sole reasoning carrier, so its Thinking must survive.expect(screen.getAllByTestId("collapsible-thinking")).toHaveLength(1);fireEvent.click(screen.getByTestId("collapsible-thinking-toggle"));expect(diff --git a/__tests__/components/conversation-events/chat/messages-model-messages.test.tsx b/__tests__/components/conversation-events/chat/messages-model-messages.test.tsxindex 72fa22afb0..dd9e450046 100644--- a/__tests__/components/conversation-events/chat/messages-model-messages.test.tsx+++ b/__tests__/components/conversation-events/chat/messages-model-messages.test.tsx@@ -37,7 +37,7 @@ const makeBashAction = (id: string): ActionEvent<ExecuteBashAction> => ({});const makeStreamingDelta = (content: string): StreamingDeltaEvent => ({- id: "delta-1",+ id: "item-1",timestamp: "2026-06-12T12:00:00Z",source: "agent",kind: "StreamingDeltaEvent",@@ -62,7 +62,7 @@ describe("Messages model entries", () => {expect(screen.getByTestId("model-messages")).toBeInTheDocument();});- it("rerenders when a streaming delta is compacted under the same event id", () => {+ it("rerenders as a streaming slot accumulates under the same event id", async () => {const firstDelta = makeStreamingDelta("First");const mergedDelta = makeStreamingDelta("First second third");@@ -74,6 +74,7 @@ describe("Messages model entries", () => {rerender(<Messages messages={[mergedDelta]} allEvents={[mergedDelta]} />);- expect(screen.getByText("First second third")).toBeInTheDocument();+ // Revealed on a clock (#15493), so the added text lands over a frame or two.+ expect(await screen.findByText("First second third")).toBeInTheDocument();});});diff --git a/__tests__/components/onboarding/onboarding-modal.test.tsx b/__tests__/components/onboarding/onboarding-modal.test.tsxindex a0fcdd513c..19424b2b06 100644--- a/__tests__/components/onboarding/onboarding-modal.test.tsx+++ b/__tests__/components/onboarding/onboarding-modal.test.tsx@@ -233,7 +233,7 @@ beforeEach(() => {if (options?.host?.startsWith("https://127.0.0.1:8000")) {return Promise.reject(new Error("Failed to fetch"));}- return Promise.resolve({ version: "1.28.0" });+ return Promise.resolve({ version: "1.48.0" });});// ChooseAgentStep's Next button now persists the selection via// saveSettings before advancing. Stub it so the rest of the flowdiff --git a/__tests__/contexts/conversation-websocket-context.test.tsx b/__tests__/contexts/conversation-websocket-context.test.tsxindex dac1c71bc4..6baf1bd9aa 100644--- a/__tests__/contexts/conversation-websocket-context.test.tsx+++ b/__tests__/contexts/conversation-websocket-context.test.tsx@@ -2,6 +2,8 @@ import React from "react";import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import { render, waitFor, act } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { readFileSync } from "node:fs";+import { resolve } from "node:path";import { createUserMessageEvent } from "test-utils";import {ConversationWebSocketProvider,@@ -28,13 +30,31 @@ import type { AppConversation } from "#/api/conversation-service/agent-server-coimport type { MessageEvent } from "#/types/agent-server/core";import { isStreamingDeltaEvent } from "#/types/agent-server/type-guards";+type QueryParams = Record<string, string | boolean>;+type CapturedWebSocketOptions = {onMessage?: (event: { data: string }) => void;- queryParams?: Record<string, string | boolean>;+ onOpen?: (event: Event) => void;+ onClose?: (event: CloseEvent) => void;+ queryParams?: QueryParams | (() => QueryParams);sessionApiKey?: string | null;};+/** Both sockets resolve their params at connect time (the resume cursor). */+const resolveQueryParams = (+ options?: { queryParams?: QueryParams | (() => QueryParams) } | null,+): QueryParams => {+ const params = options?.queryParams;+ return typeof params === "function" ? params() : (params ?? {});+};++/** Wrap a durable event the way `/sockets/session/{id}` does. */+let nextSeq = 0;+const durable = (event: unknown, seq = nextSeq++) =>+ JSON.stringify({ type: "durable", seq, event });+const wsCapture = vi.hoisted(() => ({+ hookCalls: 0,mainOnMessage: null as null | ((event: { data: string }) => void),mainOptions: null as CapturedWebSocketOptions | null,planningOnMessage: null as null | ((event: { data: string }) => void),@@ -57,27 +77,19 @@ vi.mock("#/hooks/use-websocket", () => ({if (url) {wsCapture.calls.push({ url, options });}- if (- url &&- options?.onMessage &&- options.queryParams &&- "resend_mode" in options.queryParams- ) {- wsCapture.mainOnMessage = options.onMessage;- wsCapture.mainOptions = options;- }- // The planning socket is the only connection the provider opens with- // `resend_all` (the main socket uses `resend_mode`), so its presence in- // queryParams is what distinguishes the two captured connections. If the- // planning params are ever renamed, update this discriminator too.- if (- url &&- options?.onMessage &&- options.queryParams &&- "resend_all" in options.queryParams- ) {- wsCapture.planningOnMessage = options.onMessage;- wsCapture.planningOptions = options;+ // Both sockets speak the same protocol now, so neither the URL nor the+ // query params tell them apart. Hooks run in declaration order on every+ // render β main socket first, planning second β so call parity does.+ const isMain = wsCapture.hookCalls % 2 === 0;+ wsCapture.hookCalls += 1;+ if (url && options?.onMessage) {+ if (isMain) {+ wsCapture.mainOnMessage = options.onMessage;+ wsCapture.mainOptions = options;+ } else {+ wsCapture.planningOnMessage = options.onMessage;+ wsCapture.planningOptions = options;+ }}return { socket: null, reconnect: vi.fn() };}),@@ -134,6 +146,8 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ());beforeEach(() => {+ nextSeq = 0;+ wsCapture.hookCalls = 0;wsCapture.mainOnMessage = null;wsCapture.mainOptions = null;wsCapture.planningOnMessage = null;@@ -164,6 +178,9 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()// The cached REST history page ends at the user's message β a fresh page// per conversation so we can detect cross-conversation leakage.+ // Unfiltered count = log length; the history page turns it into the+ // first-connect cursor.+ vi.spyOn(EventService, "getEventCount").mockResolvedValue(1);vi.spyOn(EventService, "searchEvents").mockImplementation(async (conversationId: string) => ({items: [createUserMessageEvent(`user-msg-${conversationId}`)],@@ -214,7 +231,7 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()// Act: the agent switches to "fast-opus" via the SwitchLLM tool.act(() => {wsCapture.mainOnMessage!({- data: JSON.stringify(makeAgentSwitchObservation("fast-opus")),+ data: durable(makeAgentSwitchObservation("fast-opus")),});});@@ -244,7 +261,7 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()await waitFor(() => expect(wsCapture.mainOptions).not.toBeNull());expect(wsCapture.mainOptions?.sessionApiKey).toBe(sessionApiKey);- expect(wsCapture.mainOptions?.queryParams).not.toHaveProperty(+ expect(resolveQueryParams(wsCapture.mainOptions)).not.toHaveProperty("session_api_key",);});@@ -284,18 +301,14 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ());await waitFor(() => expect(wsCapture.mainOptions).not.toBeNull());- // Every render's main-socket call (the one carrying `resend_mode`),+ // Every render's main-socket call (see the mock: main is the even one),// including any teardown call with an empty URL.const mainCalls = () =>- vi- .mocked(useWebSocket)- .mock.calls.filter(- ([, options]) =>- options?.queryParams && "resend_mode" in options.queryParams,- );+ vi.mocked(useWebSocket).mock.calls.filter((_, index) => index % 2 === 0);const connectedAt = mainCalls().length;- const anchor = wsCapture.mainOptions?.queryParams?.after_timestamp;- expect(anchor).toBeTruthy();+ expect(resolveQueryParams(wsCapture.mainOptions)).toHaveProperty(+ "after_seq",+ );// Act: a background refetch starts (as `refetchOnMount: "always"` fires// when returning to a conversation) and stays in flight.@@ -309,13 +322,10 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ());// Assert: since the socket connected, no render tore it down (empty URL)- // and none degraded the `since` anchor to a full resend.+ // and every call still carries the resume cursor.for (const [url, options] of mainCalls().slice(connectedAt - 1)) {- expect(url).toContain("/sockets/events/conv-refetch");- expect(options?.queryParams).toMatchObject({- resend_mode: "since",- after_timestamp: anchor,- });+ expect(url).toContain("/sockets/session/conv-refetch");+ expect(resolveQueryParams(options)).toHaveProperty("after_seq");}// The refetch settling must not churn the socket either.@@ -323,7 +333,7 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()resolveRefetch(historyPage());});const [urlAfterRefetch] = mainCalls().at(-1)!;- expect(urlAfterRefetch).toContain("/sockets/events/conv-refetch");+ expect(urlAfterRefetch).toContain("/sockets/session/conv-refetch");});it("uses the planning sub-conversation session key", async () => {@@ -367,21 +377,24 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()await waitFor(() =>expect(wsCapture.calls.some(({ url }) =>- url.endsWith("/sockets/events/planning-auth"),+ url.endsWith("/sockets/session/planning-auth"),),).toBe(true),);const planningCall = wsCapture.calls.find(({ url }) =>- url.endsWith("/sockets/events/planning-auth"),+ url.endsWith("/sockets/session/planning-auth"),);expect(planningCall?.url).toBe(- "ws://planner.example/sockets/events/planning-auth",+ "ws://planner.example/sockets/session/planning-auth",);expect(planningCall?.options?.sessionApiKey).toBe(planningSessionApiKey);- expect(planningCall?.options?.queryParams).toEqual({ resend_all: true });- expect(planningCall?.options?.queryParams).not.toHaveProperty(+ // No REST preload for the planner, so it replays the whole log.+ expect(resolveQueryParams(planningCall?.options)).toEqual({+ after_seq: "-1",+ });+ expect(resolveQueryParams(planningCall?.options)).not.toHaveProperty("session_api_key",);});@@ -494,7 +507,7 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()// Act: the agent switches model via the SwitchLLM tool.act(() => {wsCapture.mainOnMessage!({- data: JSON.stringify(makeAgentSwitchObservation("fast-opus")),+ data: durable(makeAgentSwitchObservation("fast-opus")),});});@@ -619,7 +632,7 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()const deliver = (event: unknown) =>act(() => {- wsCapture.mainOnMessage!({ data: JSON.stringify(event) });+ wsCapture.mainOnMessage!({ data: durable(event) });});it("does not re-append terminal input/output for replayed bash events", async () => {@@ -754,7 +767,7 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()act(() => {wsCapture.planningOnMessage!({- data: JSON.stringify(makeAgentError("agent-err-2", classification)),+ data: durable(makeAgentError("agent-err-2", classification)),});});@@ -801,7 +814,7 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()const deliverMain = (event: unknown) =>act(() => {- wsCapture.mainOnMessage!({ data: JSON.stringify(event) });+ wsCapture.mainOnMessage!({ data: durable(event) });});const makePlanningConversation = (id: string): AppConversation => ({@@ -951,17 +964,18 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()await waitFor(() => expect(wsCapture.planningOnMessage).not.toBeNull());// Sanity-check the captured planning socket before delivering events:- // it must be the planning connection (resend_all) so the invalidation- // below is provably scoped by the sub-conversation id, not the main one.- expect(wsCapture.planningOptions?.queryParams).toEqual({- resend_all: true,- });+ // it must be the planning connection so the invalidation below is+ // provably scoped by the sub-conversation id, not the main one.+ const planningCall = wsCapture.calls.find(({ url }) =>+ url.endsWith("/sockets/session/planning-cache"),+ );+ expect(planningCall?.options).toBe(wsCapture.planningOptions);const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries");act(() => {wsCapture.planningOnMessage!({- data: JSON.stringify({+ data: durable({id: "evt-plan-action-1",timestamp: new Date().toISOString(),source: "agent",@@ -999,7 +1013,7 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()act(() => {wsCapture.planningOnMessage!({- data: JSON.stringify(+ data: durable(makeStateUpdate("execution_status", ExecutionStatus.PAUSED),),});@@ -1116,14 +1130,23 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()expect(eventIds()).toHaveLength(2);});- const makeStreamingDelta = (id: string, content: string) => ({- id,- timestamp: new Date().toISOString(),- source: "agent",- kind: "StreamingDeltaEvent",- content,- reasoning_content: null,- });+ const itemStarted = (itemId: string, anchorSeq: number | null = null) =>+ JSON.stringify({+ type: "item_started",+ item_id: itemId,+ attempt: 1,+ ...(anchorSeq === null ? {} : { anchor_seq: anchorSeq }),+ });++ const delta = (itemId: string, content: string, order: number) =>+ JSON.stringify({+ type: "delta",+ item_id: itemId,+ attempt: 1,+ order,+ kind: "text",+ content,+ });const makeAgentMessage = (id: string, text: string): MessageEvent => ({id,@@ -1146,47 +1169,74 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()</QueryClientProvider>,);- it("buffers streaming deltas, then flushes them (reconciled) when the final message arrives", async () => {+ it("buffers deltas, then retires the slot by id when the durable message arrives", async () => {renderProviderWithUrl("conv-stream");await waitFor(() => expect(wsCapture.mainOnMessage).not.toBeNull());await waitFor(() => expect(eventIds()).toEqual(["user-msg-conv-stream"]));- // Deltas arrive: they are buffered by the batcher, NOT committed per token.+ // The slot opens before the first token; deltas are buffered by the+ // batcher, NOT committed per token.act(() => {+ wsCapture.mainOnMessage!({ data: itemStarted("agent-final") });+ wsCapture.mainOnMessage!({ data: delta("agent-final", "I'll help", 0) });wsCapture.mainOnMessage!({- data: JSON.stringify(makeStreamingDelta("d1", "I'll help")),- });- wsCapture.mainOnMessage!({- data: JSON.stringify(makeStreamingDelta("d2", " with that.")),+ data: delta("agent-final", " with that.", 1),});});+ // Slots live only in `uiEvents`; the durable log is untouched.expect(eventIds()).toEqual(["user-msg-conv-stream"]);- // The final agent message is a non-delta event: the handler flushes the- // buffered deltas first, so the message reconciles the streamed text in- // place instead of racing ahead of it.+ // The durable frame flushes the buffer first, then retires the slot on+ // `event.id === item_id` β one equality test, no text comparison.act(() => {wsCapture.mainOnMessage!({- data: JSON.stringify(- makeAgentMessage("agent-final", "I'll help with that. Done."),- ),+ data: durable(makeAgentMessage("agent-final", "I'll help with that.")),});});const { uiEvents, eventIds: ids } = useEventStore.getState();- // One reconciled agent bubble: the canonical final message supersedes the- // flushed deltas, so the streamed text renders once and is never duplicated.expect(uiEvents).toHaveLength(2);const bubble = uiEvents[1] as MessageEvent;expect(bubble.id).toBe("agent-final");- expect(bubble.llm_message.content).toEqual([- { type: "text", text: "I'll help with that. Done." },- ]);expect(uiEvents.some((event) => isStreamingDeltaEvent(event))).toBe(false);- // eventIds tracks the two durable events, never the deltas.+ // eventIds tracks the two durable events, never the slot.expect(ids.size).toBe(2);});+ it("keeps a user message that lands mid-stream below the bubble (#15433)", async () => {+ renderProviderWithUrl("conv-split");+ await waitFor(() => expect(wsCapture.mainOnMessage).not.toBeNull());+ await waitFor(() => expect(eventIds()).toEqual(["user-msg-conv-split"]));++ act(() => {+ wsCapture.mainOnMessage!({ data: itemStarted("agent-split", 0) });+ wsCapture.mainOnMessage!({ data: delta("agent-split", "First half", 0) });+ });+ act(() => {+ // A user message arrives mid-stream, sequenced after the slot's anchor.+ wsCapture.mainOnMessage!({+ data: durable(createUserMessageEvent("mid-stream"), 1),+ });+ wsCapture.mainOnMessage!({+ data: delta("agent-split", " second half", 1),+ });+ });++ // One bubble, still whole, with the interrupting message below it.+ await waitFor(() => {+ const slots = useEventStore+ .getState()+ .uiEvents.filter((event) => isStreamingDeltaEvent(event));+ expect(slots).toHaveLength(1);+ expect(slots[0].content).toBe("First half second half");+ });+ expect(useEventStore.getState().uiEvents.map((event) => event.id)).toEqual([+ "user-msg-conv-split",+ "agent-split",+ "mid-stream",+ ]);+ });+it("discards buffered deltas from the previous conversation on switch", async () => {const { rerender } = renderProviderWithUrl("conv-a");await waitFor(() => expect(wsCapture.mainOnMessage).not.toBeNull());@@ -1194,9 +1244,8 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()// Buffer deltas for A, then switch to B before they flush.act(() => {- wsCapture.mainOnMessage!({- data: JSON.stringify(makeStreamingDelta("a1", "STALE")),- });+ wsCapture.mainOnMessage!({ data: itemStarted("stale-item") });+ wsCapture.mainOnMessage!({ data: delta("stale-item", "STALE", 0) });});rerender(<QueryClientProvider client={queryClient}>@@ -1210,14 +1259,13 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ());await waitFor(() => expect(eventIds()).toEqual(["user-msg-conv-b"]));- // B streams and finalizes. If the switch had NOT reset the batcher, A's- // "STALE" delta would still be buffered and merge into B's stream here.+ // B streams and finalizes. Had the switch not reset the batcher, A's+ // "STALE" delta would still be buffered and commit here.act(() => {+ wsCapture.mainOnMessage!({ data: itemStarted("agent-b") });+ wsCapture.mainOnMessage!({ data: delta("agent-b", "fresh", 0) });wsCapture.mainOnMessage!({- data: JSON.stringify(makeStreamingDelta("b1", "fresh")),- });- wsCapture.mainOnMessage!({- data: JSON.stringify(makeAgentMessage("agent-b", "fresh.")),+ data: durable(makeAgentMessage("agent-b", "fresh.")),});});@@ -1226,15 +1274,398 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()expect((uiEvents[1] as MessageEvent).llm_message.content).toEqual([{ type: "text", text: "fresh." },]);- // The committed delta carries B's text only β had A's buffer survived the- // switch it would have merged in ahead of it as "STALEfresh".- const committedDeltas = events.filter((event) =>- isStreamingDeltaEvent(event),- );- expect(committedDeltas.map((delta) => delta.content)).toEqual(["fresh"]);+ expect(JSON.stringify(uiEvents)).not.toContain("STALE");expect(JSON.stringify(events)).not.toContain("STALE");});+ describe("session socket resume cursor", () => {+ const mainAfterSeq = () =>+ resolveQueryParams(wsCapture.mainOptions).after_seq;++ it("resumes the first connect from the history page, not the whole log", async () => {+ vi.mocked(EventService.getEventCount).mockResolvedValue(42);+ renderProviderWithUrl("conv-cursor");+ await waitFor(() => expect(wsCapture.mainOptions).not.toBeNull());++ // after_seq=-1 would replay history older than the page through+ // non-idempotent side effects (terminal, banners, client tools).+ await waitFor(() => expect(mainAfterSeq()).toBe("41"));+ });++ it("advances past each durable frame, so a reconnect resumes there", async () => {+ renderProviderWithUrl("conv-advance");+ await waitFor(() => expect(wsCapture.mainOnMessage).not.toBeNull());+ // Connect: count is 1, so the socket resumes after seq 0.+ await waitFor(() => expect(mainAfterSeq()).toBe("0"));++ act(() => {+ wsCapture.mainOnMessage!({+ data: durable(makeAgentMessage("agent-1", "hi"), 1),+ });+ wsCapture.mainOnMessage!({+ data: durable(makeAgentMessage("agent-2", "hi"), 2),+ });+ });++ expect(mainAfterSeq()).toBe("2");+ });++ it("does not resume past a durable frame still in flight", async () => {+ renderProviderWithUrl("conv-gap");+ await waitFor(() => expect(wsCapture.mainOnMessage).not.toBeNull());+ await waitFor(() => expect(mainAfterSeq()).toBe("0"));++ // agent-server 1.47.0 delivers a state update (#2) ahead of the user+ // message persisted before it (#1). If the socket drops here, resuming+ // after #2 would lose #1 for good.+ act(() => {+ wsCapture.mainOnMessage!({+ data: durable(makeAgentMessage("state-2", "later"), 2),+ });+ });+ expect(mainAfterSeq()).toBe("0");++ act(() => {+ wsCapture.mainOnMessage!({+ data: durable(makeAgentMessage("msg-1", "earlier"), 1),+ });+ wsCapture.mainOnMessage!({+ data: durable(makeAgentMessage("state-2", "later"), 2),+ });+ });+ expect(mainAfterSeq()).toBe("2");+ });++ it("does not carry a cursor into the next conversation", async () => {+ const { rerender } = renderProviderWithUrl("conv-first");+ await waitFor(() => expect(wsCapture.mainOnMessage).not.toBeNull());+ await waitFor(() => expect(mainAfterSeq()).toBe("0"));+ act(() => {+ wsCapture.mainOnMessage!({+ data: durable(makeAgentMessage("agent-first", "hi"), 1),+ });+ });+ expect(mainAfterSeq()).toBe("1");++ vi.mocked(EventService.getEventCount).mockResolvedValue(3);+ rerender(+ <QueryClientProvider client={queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-second"+ conversationUrl="http://localhost/api"+ >+ <div />+ </ConversationWebSocketProvider>+ </QueryClientProvider>,+ );++ // Resolving params starts the cursor, exactly as a connect does, so wait+ // until conv-second's socket actually exists (it is gated on history).+ await waitFor(() =>+ expect(wsCapture.calls.at(-1)?.url ?? "").toContain("conv-second"),+ );+ // conv-first's position means nothing in conv-second's log.+ expect(mainAfterSeq()).toBe("2");+ });+ });++ it("does not carry the planner's cursor into a different planning conversation", async () => {+ const planner = (id: string): AppConversation =>+ ({+ id,+ conversation_url: `http://planner.example/api/conversations/${id}`,+ session_api_key: null,+ }) as AppConversation;+ const renderWith = (plannerId: string) => (+ <QueryClientProvider client={queryClient}>+ <ConversationWebSocketProvider+ conversationId="conv-plan-switch"+ conversationUrl="http://localhost/api"+ subConversationIds={[plannerId]}+ subConversations={[planner(plannerId)]}+ >+ <div />+ </ConversationWebSocketProvider>+ </QueryClientProvider>+ );+ const plannerAfterSeq = () =>+ resolveQueryParams(wsCapture.planningOptions).after_seq;++ const { rerender } = render(renderWith("planner-a"));+ await waitFor(() => expect(wsCapture.planningOnMessage).not.toBeNull());+ expect(plannerAfterSeq()).toBe("-1");+ act(() => {+ wsCapture.planningOnMessage!({+ data: durable(makeAgentMessage("plan-0", "a"), 0),+ });+ });+ expect(plannerAfterSeq()).toBe("0");++ rerender(renderWith("planner-b"));+ await waitFor(() =>+ expect(+ wsCapture.calls.some(({ url }) => url.endsWith("/planner-b")),+ ).toBe(true),+ );+ expect(plannerAfterSeq()).toBe("-1");+ });++ describe("streaming slots across reconnects", () => {+ const slots = () =>+ useEventStore+ .getState()+ .uiEvents.filter((event) => isStreamingDeltaEvent(event));++ it("leaves no orphaned bubble when the socket drops mid-stream", async () => {+ renderProviderWithUrl("conv-drop");+ await waitFor(() => expect(wsCapture.mainOnMessage).not.toBeNull());+ await waitFor(() => expect(eventIds()).toEqual(["user-msg-conv-drop"]));++ act(() => {+ wsCapture.mainOnMessage!({ data: itemStarted("agent-drop") });+ wsCapture.mainOnMessage!({ data: delta("agent-drop", "half a", 0) });+ });+ await waitFor(() => expect(slots()).toHaveLength(1));++ // Connection lost: progress frames are never replayed, so the slot goes.+ act(() => {+ wsCapture.mainOptions!.onClose!({} as CloseEvent);+ });+ expect(slots()).toHaveLength(0);++ // Reconnect. The stream is still live, so its next delta reopens the+ // bubble, and the finished message retires it exactly once.+ act(() => {+ wsCapture.mainOptions!.onOpen!({} as Event);+ wsCapture.mainOnMessage!({ data: delta("agent-drop", " sentence", 1) });+ wsCapture.mainOnMessage!({+ data: durable(makeAgentMessage("agent-drop", "half a sentence")),+ });+ });++ const { uiEvents } = useEventStore.getState();+ expect(slots()).toHaveLength(0);+ expect(uiEvents.map((event) => event.id)).toEqual([+ "user-msg-conv-drop",+ "agent-drop",+ ]);+ });++ it("streams a reply whose item_started went by before the socket connected", async () => {+ renderProviderWithUrl("conv-late");+ await waitFor(() => expect(wsCapture.mainOnMessage).not.toBeNull());++ // Recorded on agent-server 1.47.0: a conversation started from the home+ // page begins streaming before its page's socket opens.+ act(() => {+ wsCapture.mainOnMessage!({ data: delta("agent-late", "Let me", 3) });+ wsCapture.mainOnMessage!({ data: delta("agent-late", " check", 4) });+ });+ await waitFor(() => expect(slots()[0]?.content).toBe("Let me check"));++ act(() => {+ wsCapture.mainOnMessage!({+ data: durable(makeAgentMessage("agent-late", "Let me check.")),+ });+ // A straggler overtaken by its own durable event must not reopen it.+ wsCapture.mainOnMessage!({ data: delta("agent-late", " late", 5) });+ });+ await new Promise((r) => setTimeout(r, 50));+ expect(slots()).toHaveLength(0);+ });++ it("drops the slot on item_aborted", async () => {+ renderProviderWithUrl("conv-abort");+ await waitFor(() => expect(wsCapture.mainOnMessage).not.toBeNull());++ act(() => {+ wsCapture.mainOnMessage!({ data: itemStarted("agent-abort") });+ wsCapture.mainOnMessage!({ data: delta("agent-abort", "partial", 0) });+ wsCapture.mainOnMessage!({+ data: JSON.stringify({+ type: "item_aborted",+ item_id: "agent-abort",+ attempt: 1,+ reason: "cancelled",+ }),+ });+ });++ expect(slots()).toHaveLength(0);+ });++ it("re-streams a retry in the same bubble instead of appending to it", async () => {+ renderProviderWithUrl("conv-retry");+ await waitFor(() => expect(wsCapture.mainOnMessage).not.toBeNull());++ act(() => {+ wsCapture.mainOnMessage!({ data: itemStarted("agent-retry") });+ wsCapture.mainOnMessage!({+ data: delta("agent-retry", "first try", 0),+ });+ wsCapture.mainOnMessage!({+ data: JSON.stringify({+ type: "item_started",+ item_id: "agent-retry",+ attempt: 2,+ }),+ });+ wsCapture.mainOnMessage!({+ data: JSON.stringify({+ type: "delta",+ item_id: "agent-retry",+ attempt: 2,+ order: 0,+ kind: "text",+ content: "second try",+ }),+ });+ });++ await waitFor(() => expect(slots()[0]?.content).toBe("second try"));+ expect(slots()).toHaveLength(1);+ });+ });++ // Frames recorded from a real agent-server 1.47.0 session socket, driven by a+ // word-by-word streaming mock LLM. Large strings are trimmed; nothing else is+ // edited, so these pin the client to what the server actually sends β+ // including durable frames that arrive out of seq order.+ describe("recorded agent-server 1.47.0 transcripts", () => {+ type Frame = {+ type: string;+ seq?: number;+ item_id?: string;+ event?: { id: string; source?: string; llm_message?: unknown };+ };+ const load = <T,>(name: string): T =>+ JSON.parse(+ readFileSync(+ resolve(process.cwd(), "__tests__/fixtures/session-socket", name),+ "utf8",+ ),+ );+ const feed = (frames: Frame[]) =>+ act(() => {+ for (const frame of frames) {+ wsCapture.mainOnMessage!({ data: JSON.stringify(frame) });+ }+ });+ const slots = () =>+ useEventStore+ .getState()+ .uiEvents.filter((event) => isStreamingDeltaEvent(event));+ const retiringIds = (frames: Frame[]) =>+ frames.filter((f) => f.type === "item_started").map((f) => f.item_id!);++ beforeEach(() => {+ // REST history comes from the same server clock as the recording (naive+ // local time), and predates it.+ vi.mocked(EventService.searchEvents).mockImplementation(+ async (conversationId: string) => ({+ items: [+ {+ ...createUserMessageEvent(`user-msg-${conversationId}`),+ timestamp: "2026-09-16T10:00:00.000000",+ },+ ],+ next_page_id: null,+ }),+ );+ });++ it("keeps one whole bubble when a user message lands mid-stream (#15433)", async () => {+ const frames = load<Frame[]>(+ "mid-stream-user-message.agent-server-1.47.0.json",+ );+ renderProviderWithUrl("conv-recorded-a");+ await waitFor(() => expect(wsCapture.mainOnMessage).not.toBeNull());+ await waitFor(() => expect(wsCapture.mainOptions).not.toBeNull());+ resolveQueryParams(wsCapture.mainOptions); // connect++ const midUser = frames.findIndex(+ (f) => f.type === "durable" && f.event?.source === "user" && f.seq! > 1,+ );+ expect(midUser).toBeGreaterThan(+ frames.findIndex((f) => f.type === "item_started"),+ );++ // Up to and including the first delta after the interrupting message.+ feed(frames.slice(0, midUser + 2));+ await waitFor(() =>+ expect(slots()[0]?.content).toBe("Let me check the workspace"),+ );+ expect(slots()).toHaveLength(1);+ const order = useEventStore.getState().uiEvents.map((e) => e.id);+ expect(order.indexOf(slots()[0].id)).toBeLessThan(+ order.indexOf(frames[midUser].event!.id),+ );++ feed(frames.slice(midUser + 2));+ await waitFor(() => expect(slots()).toHaveLength(0));++ const { events } = useEventStore.getState();+ const ids = events.map((e) => e.id);+ for (const itemId of retiringIds(frames)) {+ expect(ids.filter((id) => id === itemId)).toHaveLength(1);+ }+ expect(+ events.filter((e) => e.source === "agent" && "llm_message" in e),+ ).toHaveLength(1);+ // The cursor survived the out-of-order delivery and reached the end.+ const lastSeq = Math.max(+ ...frames.filter((f) => f.type === "durable").map((f) => f.seq!),+ );+ expect(resolveQueryParams(wsCapture.mainOptions).after_seq).toBe(+ String(lastSeq),+ );+ });++ it("leaves no orphan and loses nothing across a real mid-stream reconnect", async () => {+ const { before, resumeAfterSeq, after } = load<{+ before: Frame[];+ resumeAfterSeq: number;+ after: Frame[];+ }>("reconnect-mid-stream.agent-server-1.47.0.json");+ renderProviderWithUrl("conv-recorded-b");+ await waitFor(() => expect(wsCapture.mainOnMessage).not.toBeNull());+ await waitFor(() => expect(wsCapture.mainOptions).not.toBeNull());+ resolveQueryParams(wsCapture.mainOptions); // connect++ feed(before);+ await waitFor(() => expect(slots()).toHaveLength(1));+ const openItem = slots()[0].id;++ // The client computes the same resume point the recording used.+ act(() => {+ wsCapture.mainOptions!.onClose!({} as CloseEvent);+ });+ expect(slots()).toHaveLength(0);+ expect(resolveQueryParams(wsCapture.mainOptions).after_seq).toBe(+ String(resumeAfterSeq),+ );+ act(() => {+ wsCapture.mainOptions!.onOpen!({} as Event);+ });++ feed(after);+ await waitFor(() => {+ expect(slots()).toHaveLength(0);+ });+ const ids = useEventStore.getState().events.map((e) => e.id);+ expect(ids.filter((id) => id === openItem)).toHaveLength(1);+ const serverIds = new Set(+ [...before, ...after]+ .filter((f) => f.type === "durable")+ .map((f) => f.event!.id),+ );+ for (const id of serverIds) {+ expect(ids).toContain(id);+ }+ expect(new Set(ids).size).toBe(ids.length);+ });+ });+it("consumes the optimistic pending bubble when the echoed user message arrives via REST preload", async () => {// Arrange: a cloud start-task conversation left a "Sendingβ¦" bubble whose// content matches the first message the server has already persisted. Withdiff --git a/__tests__/contexts/conversation-websocket-provider.behavior.test.tsx b/__tests__/contexts/conversation-websocket-provider.behavior.test.tsxindex c88b10333e..c833f3b39d 100644--- a/__tests__/contexts/conversation-websocket-provider.behavior.test.tsx+++ b/__tests__/contexts/conversation-websocket-provider.behavior.test.tsx@@ -53,7 +53,7 @@ const socketCapture = vi.hoisted(() => ({const historyCapture = vi.hoisted(() => ({result: {data: { events: [] as OpenHandsEvent[] } as- | { events: OpenHandsEvent[] }+ | { events: OpenHandsEvent[]; afterSeq?: number | null }| undefined,isPending: false,isFetching: false,@@ -292,20 +292,38 @@ function planningOptions(): WebSocketHookOptions {return socketCapture.planningOptions!;}-function dispatchMain(event: unknown) {+/** Resolve a socket's query params the way `useWebSocket` does at connect. */+function queryParamsOf(options: WebSocketHookOptions) {+ const params = options.queryParams;+ return typeof params === "function" ? params() : params;+}++let nextSeq = 0;++/** Send a raw session-socket frame (progress frames, malformed payloads). */+function dispatchMainFrame(frame: unknown) {act(() => {- mainOptions().onMessage?.({ data: JSON.stringify(event) } as MessageEvent);+ mainOptions().onMessage?.({ data: JSON.stringify(frame) } as MessageEvent);});}-function dispatchPlanning(event: unknown) {+function dispatchPlanningFrame(frame: unknown) {act(() => {planningOptions().onMessage?.({- data: JSON.stringify(event),+ data: JSON.stringify(frame),} as MessageEvent);});}+/** Deliver an event the way `/sockets/session/{id}` does: as a durable frame. */+function dispatchMain(event: unknown) {+ dispatchMainFrame({ type: "durable", seq: nextSeq++, event });+}++function dispatchPlanning(event: unknown) {+ dispatchPlanningFrame({ type: "durable", seq: nextSeq++, event });+}+describe("Conversation websocket behavior", () => {beforeEach(() => {socketCapture.callIndex = 0;@@ -321,6 +339,7 @@ describe("Conversation websocket behavior", () => {socketCapture.readConversationFile.mockReset();socketCapture.trackError.mockReset();socketCapture.launchChild.mockReset().mockResolvedValue(undefined);+ nextSeq = 0;historyCapture.result = {data: { events: [] },isPending: false,@@ -392,7 +411,7 @@ describe("Conversation websocket behavior", () => {it("hydrates history, consumes matching optimistic messages, and subscribes after the latest event", async () => {const first = makeMessageEvent("01", "assistant", ["first"]);const latest = makeMessageEvent("02", "user", ["hello", " world"]);- historyCapture.result.data = { events: [first, latest] };+ historyCapture.result.data = { events: [first, latest], afterSeq: 41 };const consumeMatchingPendingMessage = vi.spyOn(useOptimisticUserMessageStore.getState(),"consumeMatchingPendingMessage",@@ -439,17 +458,14 @@ describe("Conversation websocket behavior", () => {timestamp: expect.any(String),}),);- expect(socketCapture.mainUrl).toContain("/sockets/events/conv-main");+ expect(socketCapture.mainUrl).toContain("/sockets/session/conv-main");// The session key is now passed via the dedicated `sessionApiKey` option// rather than folded into the query string.- expect(mainOptions().queryParams).toEqual({- resend_mode: "since",- after_timestamp: latest.timestamp,- });+ // Resumes after the last seq the history page covered, not a timestamp.+ expect(queryParamsOf(mainOptions())).toEqual({ after_seq: "41" });expect(mainOptions().sessionApiKey).toBe("session-key");- expect(planningOptions().queryParams).toEqual({- resend_all: true,- });+ // The planner has no REST preload, so it replays its whole log.+ expect(queryParamsOf(planningOptions())).toEqual({ after_seq: "-1" });expect(planningOptions().sessionApiKey).toBe("session-key");expect(mainOptions().reconnect).toEqual({ enabled: true });expect(planningOptions().reconnect).toEqual({ enabled: true });@@ -465,7 +481,7 @@ describe("Conversation websocket behavior", () => {renderProvider();expect(socketCapture.mainUrl).toBe("");- expect(mainOptions().queryParams).toEqual({ resend_mode: "all" });+ expect(queryParamsOf(mainOptions())).toEqual({ after_seq: "-1" });expect(screen.getByTestId("connection-state")).toHaveTextContent("CONNECTING",);@@ -489,8 +505,8 @@ describe("Conversation websocket behavior", () => {renderProvider();- expect(socketCapture.mainUrl).toContain("/sockets/events/conv-main");- expect(mainOptions().queryParams).toEqual({ resend_mode: "all" });+ expect(socketCapture.mainUrl).toContain("/sockets/session/conv-main");+ expect(queryParamsOf(mainOptions())).toEqual({ after_seq: "-1" });});it("does not build socket URLs without complete conversation coordinates", () => {@@ -526,7 +542,7 @@ describe("Conversation websocket behavior", () => {socketCapture.callIndex = 0;historyCapture.result.data = undefined;const first = renderProvider();- expect(mainOptions().queryParams).toEqual({ resend_mode: "all" });+ expect(queryParamsOf(mainOptions())).toEqual({ after_seq: "-1" });expect(addEvents).not.toHaveBeenCalled();first.unmount();@@ -595,7 +611,7 @@ describe("Conversation websocket behavior", () => {const latest = makeMessageEvent("07", "assistant", ["fresh tail"]);historyCapture.result = {- data: { events: [latest] },+ data: { events: [latest], afterSeq: 6 },isPending: false,isFetching: false,isError: false,@@ -614,16 +630,13 @@ describe("Conversation websocket behavior", () => {await waitFor(() =>expect(useEventStore.getState().events).toHaveLength(1),);- expect(socketCapture.mainUrl).toContain("/sockets/events/conv-main");- expect(mainOptions().queryParams).toEqual({- resend_mode: "since",- after_timestamp: latest.timestamp,- });+ expect(socketCapture.mainUrl).toContain("/sockets/session/conv-main");+ expect(queryParamsOf(mainOptions())).toEqual({ after_seq: "6" });expect(- Object.hasOwn(mainOptions().queryParams ?? {}, "session_api_key"),+ Object.hasOwn(queryParamsOf(mainOptions()) ?? {}, "session_api_key"),).toBe(false);expect(- Object.hasOwn(planningOptions().queryParams ?? {}, "session_api_key"),+ Object.hasOwn(queryParamsOf(planningOptions()) ?? {}, "session_api_key"),).toBe(false);});@@ -646,7 +659,7 @@ describe("Conversation websocket behavior", () => {);expect(socketCapture.planningUrl).toContain(- "/sockets/events/conv-planning",+ "/sockets/session/conv-planning",);});@@ -1784,12 +1797,16 @@ describe("Conversation websocket behavior", () => {useErrorMessageStore.getState().setErrorMessage("disconnected", "connection");- const dispatch = source === "main" ? dispatchMain : dispatchPlanning;+ const dispatch =+ source === "main" ? dispatchMainFrame : dispatchPlanningFrame;+ dispatch({ type: "item_started", item_id: "delta", attempt: 1 });dispatch({- ...baseEvent("delta", "agent"),- kind: "StreamingDeltaEvent",+ type: "delta",+ item_id: "delta",+ attempt: 1,+ order: 0,+ kind: "text",content: "Streaming",- reasoning_content: null,});expect(useEventStore.getState().eventIds.has("delta")).toBe(false);act(() => {@@ -1810,11 +1827,18 @@ describe("Conversation websocket behavior", () => {it("flushes planning deltas before later events and ignores replayed error side effects", () => {vi.spyOn(window, "requestAnimationFrame").mockReturnValue(1);const view = renderProvider({ subConversations: [makeSubConversation()] });- dispatchPlanning({- ...baseEvent("delta-plan", "agent"),- kind: "StreamingDeltaEvent",+ dispatchPlanningFrame({+ type: "item_started",+ item_id: "delta-plan",+ attempt: 1,+ });+ dispatchPlanningFrame({+ type: "delta",+ item_id: "delta-plan",+ attempt: 1,+ order: 0,+ kind: "text",content: "Planning",- reasoning_content: null,});view.rerender(<QueryClientProvider client={view.queryClient}>@@ -1840,8 +1864,15 @@ describe("Conversation websocket behavior", () => {classification,};dispatchPlanning(error);- expect(useEventStore.getState().uiEvents[0]).toMatchObject({- kind: "StreamingDeltaEvent",+ // requestAnimationFrame never fires here, so the slot only holds the+ // streamed text if the durable frame flushed the buffer before it.+ expect(+ useEventStore+ .getState()+ .uiEvents.find(+ (event) => "kind" in event && event.kind === "StreamingDeltaEvent",+ ),+ ).toMatchObject({content: "Planning",isFromPlanningAgent: true,});diff --git a/__tests__/fixtures/session-socket/mid-stream-user-message.agent-server-1.47.0.json b/__tests__/fixtures/session-socket/mid-stream-user-message.agent-server-1.47.0.jsonnew file mode 100644index 0000000000..43268c5812--- /dev/null+++ b/__tests__/fixtures/session-socket/mid-stream-user-message.agent-server-1.47.0.json@@ -0,0 +1 @@+[{"type":"sync","from_seq":-1},{"type":"transient","event":{"id":"04af4c99-ff8a-41bd-b583-38607df06a00","timestamp":"2026-09-16T10:09:28.599765","source":"environment","key":"full_state","value":{"id":"e837e70b-ac76-457c-9e99-1a42d8e250fe","agent":{"llm":{"model":"openai/mock","api_key":"**********","auth_type":"api_key","base_url":"http://127.0.0.1:28100/v1","openrouter_site_url":"https://docs.all-hands.dev/","openrouter_app_name":"OpenHands","num_retries":5,"retry_multiplier":8,"retry_min_wait":8,"retry_max_wait":64,"timeout":300,"max_message_chars":30000,"api_mode":"auto","capability_overrides":{},"stream":true,"drop_params":true,"modify_params":true,"disable_stop_word":false,"caching_prompt":true,"log_completions":false,"log_completions_folder":"logs/completions","native_tool_calling":true,"reasoning_effort":"high","enable_encrypted_reasoning":true,"prompt_cache_retention":"24h","extended_thinking_budget":200000,"usage_id":"agent","litellm_extra_body":{},"is_subscription":false},"tools":[{"name":"terminal","params":{}}],"mcp_config":{},"include_default_tools":["FinishTool","ThinkTool"],"system_prompt_filename":"system_prompt.j2","security_policy_filename":"security_policy.j2","system_prompt_kwargs":{"llm_security_analyzer":true},"tool_concurrency_limit":1,"kind":"Agent"},"workspace":{"working_dir":"/workspace/project","kind":"LocalWorkspace"},"persistence_dir":"workspace/conversations/e837e70bac76457c9e991a42d8e250fe","max_iterations":500,"stuck_detection":true,"execution_status":"idle","confirmation_policy":{"kind":"NeverConfirm"},"activated_knowledge_skills":[],"activated_path_rules":[],"invoked_skills":[],"blocked_actions":{},"blocked_messages":{},"head_is_empty":false,"stats":{"usage_to_metrics":{}},"secret_registry":{"secret_sources":{}},"tags":{},"agent_state":{}},"kind":"ConversationStateUpdateEvent"}},{"type":"durable","seq":0,"event":{"id":"227a73d4-391c-4934-aec8-80bf4b0fe252","timestamp":"2026-09-16T10:09:29.271594","source":"agent","system_prompt":{"cache_prompt":false,"type":"text","text":"<SOUL>\nYou are OpenHands agent, a helpful AI assistant that can interact with a computer to solve tasks.\n</SOUL>\n\n<ROLE>\n* Your primary role is to assist users by executing commands, modifying code, aβ¦[trimmed]"},"tools":[{"description":"Execute a shell command in the terminal within a persistent shell session.\n\n\n### Command Execution\n* One command at a time: You can only execute one shell command at a time.\n If you need to run multiβ¦[trimmed]","action_type":"TerminalAction","observation_type":"TerminalObservation","annotations":{"title":"terminal","readOnlyHint":false,"destructiveHint":true,"idempotentHint":false,"openWorldHint":true},"kind":"TerminalTool","title":"terminal"},{"description":"Signals the completion of the current task or conversation.\n\nUse this tool when:\n- You have successfully completed the user's requested task\n- You cannot proceed further due to technical limitations or missing information\n\nThe message should include:\n- A clear summary of actions taken and their results\n- Any next steps for the user\n- Explanation if you're unable to complete the task\n- Any follow-up questions if more information is needed\n","action_type":"FinishAction","observation_type":"FinishObservation","annotations":{"title":"finish","readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false},"kind":"FinishTool","title":"finish"},{"description":"Use the tool to think about something. It will not obtain new information or make any changes to the repository, but just log the thought. Use it when complex reasoning or brainstorming is needed.\n\nCommon use cases:\n1. When exploring a repository and discovering the source of a bug, call this tool to brainstorm several unique ways of fixing the bug, and assess which change(s) are likely to be simplest and most effective.\n2. After receiving test results, use this tool to brainstorm ways to fix failing tests.\n3. When planning a complex refactoring, use this tool to outline different approaches and their tradeoffs.\n4. When designing a new feature, use this tool to think through architecture decisions and implementation details.\n5. When debugging a complex issue, use this tool to organize your thoughts and hypotheses.\n\nThe tool simply logs your thought process for better transparency and does not execute any code or make changes.","action_type":"ThinkAction","observation_type":"ThinkObservation","annotations":{"readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false},"kind":"ThinkTool","title":"think"},{"description":"Ask a saved vision-capable LLM profile to inspect an image from the latest user message and return a text answer.\n\nUse this when the current model cannot understand images, the latest user message includes an image, and visual details are needed to answer. The current model should pass the image_index shown in the user message and a specific question for the vision model. The cost of this vision model call is tracked in the same conversation stats.\n\nAvailable vision-capable profiles:\n- gpt-5.6-sol","action_type":"VisionInspectAction","observation_type":"VisionInspectObservation","annotations":{"readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":true},"kind":"VisionInspectTool","title":"inspect_image_with_vision"}],"kind":"SystemPromptEvent"}},{"type":"durable","seq":2,"event":{"id":"3372cc4a-a1f7-447b-82a1-6dc05b874c02","timestamp":"2026-09-16T10:09:29.278874","source":"environment","parent_id":"404fb49c-da1c-4539-a797-465979711bc1","key":"last_user_message_id","value":"404fb49c-da1c-4539-a797-465979711bc1","kind":"ConversationStateUpdateEvent"}},{"type":"durable","seq":1,"event":{"id":"404fb49c-da1c-4539-a797-465979711bc1","timestamp":"2026-09-16T10:09:29.276674","source":"user","parent_id":"227a73d4-391c-4934-aec8-80bf4b0fe252","llm_message":{"role":"user","content":[{"cache_prompt":false,"type":"text","text":"please check the workspace"}],"thinking_blocks":[]},"activated_skills":[],"extended_content":[],"kind":"MessageEvent"}},{"type":"durable","seq":3,"event":{"id":"cb8a9e55-4693-4f51-8df1-f97d3187c98f","timestamp":"2026-09-16T10:09:29.287229","source":"environment","parent_id":"404fb49c-da1c-4539-a797-465979711bc1","key":"execution_status","value":"running","kind":"ConversationStateUpdateEvent"}},{"type":"durable","seq":4,"event":{"id":"c4acef4e-30aa-4213-8a17-86db719f6535","timestamp":"2026-09-16T10:09:29.292771","source":"environment","parent_id":"404fb49c-da1c-4539-a797-465979711bc1","key":"stats","value":{"usage_to_metrics":{"agent":{"model_name":"openai/mock","accumulated_cost":0,"max_budget_per_task":null,"accumulated_token_usage":{"model":"openai/mock","prompt_tokens":1,"completion_tokens":1,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":2,"response_id":""}}}},"kind":"ConversationStateUpdateEvent"}},{"type":"item_started","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"anchor_seq":4},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":0,"kind":"text","content":"Let","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":1,"kind":"text","content":" me","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":2,"kind":"text","content":" check","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":3,"kind":"text","content":" the","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"durable","seq":6,"event":{"id":"6b81ccf1-661f-4ef7-9fd7-57920363ae56","timestamp":"2026-09-16T10:09:29.745960","source":"environment","parent_id":"969de38f-0636-4638-b7ab-a18f370d9c3e","key":"last_user_message_id","value":"969de38f-0636-4638-b7ab-a18f370d9c3e","kind":"ConversationStateUpdateEvent"}},{"type":"durable","seq":5,"event":{"id":"969de38f-0636-4638-b7ab-a18f370d9c3e","timestamp":"2026-09-16T10:09:29.742598","source":"user","parent_id":"404fb49c-da1c-4539-a797-465979711bc1","llm_message":{"role":"user","content":[{"cache_prompt":false,"type":"text","text":"also, keep it short"}],"thinking_blocks":[]},"activated_skills":[],"extended_content":[],"kind":"MessageEvent"}},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":4,"kind":"text","content":" workspace","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":5,"kind":"text","content":" first","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":6,"kind":"text","content":" so","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":7,"kind":"text","content":" I","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":8,"kind":"text","content":" know","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":9,"kind":"text","content":" what","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":10,"kind":"text","content":" files","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":11,"kind":"text","content":" are","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":12,"kind":"text","content":" there","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":13,"kind":"text","content":" before","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":14,"kind":"text","content":" answering","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":15,"kind":"text","content":" you","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"delta","item_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","attempt":1,"order":16,"kind":"text","content":" properly.","chunk_id":"chatcmpl-09c366db","choice_index":0},{"type":"durable","seq":7,"event":{"id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","timestamp":"2026-09-16T10:09:31.425272","source":"agent","parent_id":"969de38f-0636-4638-b7ab-a18f370d9c3e","thought":[{"cache_prompt":false,"type":"text","text":"Let me check the workspace first so I know what files are there before answering you properly."}],"thinking_blocks":[],"action":{"command":"ls","is_input":false,"reset":false,"kind":"TerminalAction"},"tool_name":"terminal","tool_call_id":"call_44aea1","tool_call":{"id":"call_44aea1","name":"terminal","arguments":"{\"command\": \"ls\"}","origin":"completion"},"llm_response_id":"chatcmpl-09c366db","security_risk":"UNKNOWN","summary":"terminal: {\"command\": \"ls\"}","kind":"ActionEvent"}},{"type":"durable","seq":8,"event":{"id":"30bed2b8-2ad0-4604-a256-dec53d7eb214","timestamp":"2026-09-16T10:09:32.016174","source":"environment","parent_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","tool_name":"terminal","tool_call_id":"call_44aea1","observation":{"content":[{"cache_prompt":false,"type":"text","text":""}],"is_error":false,"command":"ls","exit_code":0,"timeout":false,"metadata":{"exit_code":0,"pid":-1,"username":"user","hostname":"Vascos-MacBook-Pro","working_dir":"/workspace/project","py_interpreter_path":"/opt/agent-server/bin/python","prefix":"","suffix":"\n[The command completed with exit code 0.]"},"kind":"TerminalObservation"},"action_id":"a628ac81-f7f2-4f49-90d2-cc1aab0731d5","extended_content":[],"kind":"ObservationEvent"}},{"type":"durable","seq":9,"event":{"id":"135110fe-0dc9-4bd0-bdd3-3df41044aecf","timestamp":"2026-09-16T10:09:31.424738","source":"environment","parent_id":"30bed2b8-2ad0-4604-a256-dec53d7eb214","key":"stats","value":{"usage_to_metrics":{"agent":{"model_name":"openai/mock","accumulated_cost":0,"max_budget_per_task":null,"accumulated_token_usage":{"model":"openai/mock","prompt_tokens":3238,"completion_tokens":48,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":3284,"response_id":""}}}},"kind":"ConversationStateUpdateEvent"}},{"type":"item_started","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"anchor_seq":9},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":0,"kind":"text","content":"All","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":1,"kind":"text","content":" done.","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":2,"kind":"text","content":" The","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":3,"kind":"text","content":" workspace","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":4,"kind":"text","content":" looks","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":5,"kind":"text","content":" healthy","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":6,"kind":"text","content":" and","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":7,"kind":"text","content":" I","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":8,"kind":"text","content":" found","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":9,"kind":"text","content":" nothing","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":10,"kind":"text","content":" unusual","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":11,"kind":"text","content":" in","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":12,"kind":"text","content":" the","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":13,"kind":"text","content":" files","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":14,"kind":"text","content":" I","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":15,"kind":"text","content":" inspected","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":16,"kind":"text","content":" just","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"delta","item_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","attempt":1,"order":17,"kind":"text","content":" now.","chunk_id":"chatcmpl-00c9083e","choice_index":0},{"type":"durable","seq":10,"event":{"id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","timestamp":"2026-09-16T10:09:34.279024","source":"agent","parent_id":"30bed2b8-2ad0-4604-a256-dec53d7eb214","llm_message":{"role":"assistant","content":[{"cache_prompt":false,"type":"text","text":"All done. The workspace looks healthy and I found nothing unusual in the files I inspected just now."}],"thinking_blocks":[]},"llm_response_id":"chatcmpl-00c9083e","activated_skills":[],"extended_content":[],"kind":"MessageEvent"}},{"type":"durable","seq":11,"event":{"id":"a6664516-d6b5-4b6d-b015-54f91d286fca","timestamp":"2026-09-16T10:09:34.282286","source":"environment","parent_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","key":"execution_status","value":"finished","kind":"ConversationStateUpdateEvent"}},{"type":"durable","seq":12,"event":{"id":"926763eb-fa4f-4baa-8759-818752a93a29","timestamp":"2026-09-16T10:09:34.278585","source":"environment","parent_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","key":"stats","value":{"usage_to_metrics":{"agent":{"model_name":"openai/mock","accumulated_cost":0,"max_budget_per_task":null,"accumulated_token_usage":{"model":"openai/mock","prompt_tokens":6604,"completion_tokens":68,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":3386,"response_id":""}}}},"kind":"ConversationStateUpdateEvent"}},{"type":"transient","event":{"id":"d0480a6f-b4f3-4bdf-8e65-abcc03145e5b","timestamp":"2026-09-16T10:09:34.289167","source":"environment","key":"full_state","value":{"id":"e837e70b-ac76-457c-9e99-1a42d8e250fe","agent":{"llm":{"model":"openai/mock","api_key":"**********","auth_type":"api_key","base_url":"http://127.0.0.1:28100/v1","openrouter_site_url":"https://docs.all-hands.dev/","openrouter_app_name":"OpenHands","num_retries":5,"retry_multiplier":8,"retry_min_wait":8,"retry_max_wait":64,"timeout":300,"max_message_chars":30000,"api_mode":"auto","capability_overrides":{},"stream":true,"drop_params":true,"modify_params":true,"disable_stop_word":false,"caching_prompt":true,"log_completions":false,"log_completions_folder":"logs/completions","native_tool_calling":true,"reasoning_effort":"high","enable_encrypted_reasoning":true,"prompt_cache_retention":"24h","extended_thinking_budget":200000,"usage_id":"agent","litellm_extra_body":{},"is_subscription":false},"tools":[{"name":"terminal","params":{}}],"mcp_config":{},"include_default_tools":["FinishTool","ThinkTool"],"system_prompt_filename":"system_prompt.j2","security_policy_filename":"security_policy.j2","system_prompt_kwargs":{"llm_security_analyzer":true},"tool_concurrency_limit":1,"kind":"Agent"},"workspace":{"working_dir":"/workspace/project","kind":"LocalWorkspace"},"persistence_dir":"workspace/conversations/e837e70bac76457c9e991a42d8e250fe","max_iterations":500,"stuck_detection":true,"execution_status":"finished","confirmation_policy":{"kind":"NeverConfirm"},"activated_knowledge_skills":[],"activated_path_rules":[],"invoked_skills":[],"blocked_actions":{},"blocked_messages":{},"last_user_message_id":"969de38f-0636-4638-b7ab-a18f370d9c3e","leaf_event_id":"89ccc57c-d9df-41f2-81ee-ac2d0c13dada","head_is_empty":false,"stats":{"usage_to_metrics":{"agent":{"model_name":"openai/mock","accumulated_cost":0,"accumulated_token_usage":{"model":"openai/mock","prompt_tokens":6604,"completion_tokens":68,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":3386,"response_id":""},"costs":[],"response_latencies":[{"model":"openai/mock","latency":0.009490966796875,"response_id":"x"},{"model":"openai/mock","latency":2.122560977935791,"response_id":"chatcmpl-09c366db"},{"model":"openai/mock","latency":2.2512800693511963,"response_id":"chatcmpl-00c9083e"}],"token_usages":[{"model":"openai/mock","prompt_tokens":1,"completion_tokens":1,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":2,"response_id":"x"},{"model":"openai/mock","prompt_tokens":3237,"completion_tokens":47,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":3284,"response_id":"chatcmpl-09c366db"},{"model":"openai/mock","prompt_tokens":3366,"completion_tokens":20,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":3386,"response_id":"chatcmpl-00c9083e"}]}}},"secret_registry":{"secret_sources":{}},"tags":{},"agent_state":{}},"kind":"ConversationStateUpdateEvent"}}]\ No newline at end of filediff --git a/__tests__/fixtures/session-socket/reconnect-mid-stream.agent-server-1.47.0.json b/__tests__/fixtures/session-socket/reconnect-mid-stream.agent-server-1.47.0.jsonnew file mode 100644index 0000000000..5a678a28e4--- /dev/null+++ b/__tests__/fixtures/session-socket/reconnect-mid-stream.agent-server-1.47.0.json@@ -0,0 +1 @@+{"before":[{"type":"sync","from_seq":-1},{"type":"transient","event":{"id":"a5881f7c-d836-44e2-af85-973c5a212218","timestamp":"2026-09-16T10:09:37.053391","source":"environment","key":"full_state","value":{"id":"52e2857d-fdb3-423b-88a8-3e02ac37abb0","agent":{"llm":{"model":"openai/mock","api_key":"**********","auth_type":"api_key","base_url":"http://127.0.0.1:28100/v1","openrouter_site_url":"https://docs.all-hands.dev/","openrouter_app_name":"OpenHands","num_retries":5,"retry_multiplier":8,"retry_min_wait":8,"retry_max_wait":64,"timeout":300,"max_message_chars":30000,"api_mode":"auto","capability_overrides":{},"stream":true,"drop_params":true,"modify_params":true,"disable_stop_word":false,"caching_prompt":true,"log_completions":false,"log_completions_folder":"logs/completions","native_tool_calling":true,"reasoning_effort":"high","enable_encrypted_reasoning":true,"prompt_cache_retention":"24h","extended_thinking_budget":200000,"usage_id":"agent","litellm_extra_body":{},"is_subscription":false},"tools":[{"name":"terminal","params":{}}],"mcp_config":{},"include_default_tools":["FinishTool","ThinkTool"],"system_prompt_filename":"system_prompt.j2","security_policy_filename":"security_policy.j2","system_prompt_kwargs":{"llm_security_analyzer":true},"tool_concurrency_limit":1,"kind":"Agent"},"workspace":{"working_dir":"/workspace/project","kind":"LocalWorkspace"},"persistence_dir":"workspace/conversations/52e2857dfdb3423b88a83e02ac37abb0","max_iterations":500,"stuck_detection":true,"execution_status":"idle","confirmation_policy":{"kind":"NeverConfirm"},"activated_knowledge_skills":[],"activated_path_rules":[],"invoked_skills":[],"blocked_actions":{},"blocked_messages":{},"head_is_empty":false,"stats":{"usage_to_metrics":{}},"secret_registry":{"secret_sources":{}},"tags":{},"agent_state":{}},"kind":"ConversationStateUpdateEvent"}},{"type":"durable","seq":0,"event":{"id":"8d57312a-8984-40be-abb1-ba38eca373cb","timestamp":"2026-09-16T10:09:37.710141","source":"agent","system_prompt":{"cache_prompt":false,"type":"text","text":"<SOUL>\nYou are OpenHands agent, a helpful AI assistant that can interact with a computer to solve tasks.\n</SOUL>\n\n<ROLE>\n* Your primary role is to assist users by executing commands, modifying code, aβ¦[trimmed]"},"tools":[{"description":"Execute a shell command in the terminal within a persistent shell session.\n\n\n### Command Execution\n* One command at a time: You can only execute one shell command at a time.\n If you need to run multiβ¦[trimmed]","action_type":"TerminalAction","observation_type":"TerminalObservation","annotations":{"title":"terminal","readOnlyHint":false,"destructiveHint":true,"idempotentHint":false,"openWorldHint":true},"kind":"TerminalTool","title":"terminal"},{"description":"Signals the completion of the current task or conversation.\n\nUse this tool when:\n- You have successfully completed the user's requested task\n- You cannot proceed further due to technical limitations or missing information\n\nThe message should include:\n- A clear summary of actions taken and their results\n- Any next steps for the user\n- Explanation if you're unable to complete the task\n- Any follow-up questions if more information is needed\n","action_type":"FinishAction","observation_type":"FinishObservation","annotations":{"title":"finish","readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false},"kind":"FinishTool","title":"finish"},{"description":"Use the tool to think about something. It will not obtain new information or make any changes to the repository, but just log the thought. Use it when complex reasoning or brainstorming is needed.\n\nCommon use cases:\n1. When exploring a repository and discovering the source of a bug, call this tool to brainstorm several unique ways of fixing the bug, and assess which change(s) are likely to be simplest and most effective.\n2. After receiving test results, use this tool to brainstorm ways to fix failing tests.\n3. When planning a complex refactoring, use this tool to outline different approaches and their tradeoffs.\n4. When designing a new feature, use this tool to think through architecture decisions and implementation details.\n5. When debugging a complex issue, use this tool to organize your thoughts and hypotheses.\n\nThe tool simply logs your thought process for better transparency and does not execute any code or make changes.","action_type":"ThinkAction","observation_type":"ThinkObservation","annotations":{"readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false},"kind":"ThinkTool","title":"think"},{"description":"Ask a saved vision-capable LLM profile to inspect an image from the latest user message and return a text answer.\n\nUse this when the current model cannot understand images, the latest user message includes an image, and visual details are needed to answer. The current model should pass the image_index shown in the user message and a specific question for the vision model. The cost of this vision model call is tracked in the same conversation stats.\n\nAvailable vision-capable profiles:\n- gpt-5.6-sol","action_type":"VisionInspectAction","observation_type":"VisionInspectObservation","annotations":{"readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":true},"kind":"VisionInspectTool","title":"inspect_image_with_vision"}],"kind":"SystemPromptEvent"}},{"type":"durable","seq":2,"event":{"id":"5449c941-a3bd-4a08-a261-f59c86a83dcf","timestamp":"2026-09-16T10:09:37.716933","source":"environment","parent_id":"85640bb2-c981-4093-8e5a-a7429a28be9d","key":"last_user_message_id","value":"85640bb2-c981-4093-8e5a-a7429a28be9d","kind":"ConversationStateUpdateEvent"}},{"type":"durable","seq":1,"event":{"id":"85640bb2-c981-4093-8e5a-a7429a28be9d","timestamp":"2026-09-16T10:09:37.715039","source":"user","parent_id":"8d57312a-8984-40be-abb1-ba38eca373cb","llm_message":{"role":"user","content":[{"cache_prompt":false,"type":"text","text":"please check the workspace"}],"thinking_blocks":[]},"activated_skills":[],"extended_content":[],"kind":"MessageEvent"}},{"type":"durable","seq":3,"event":{"id":"700ee26a-ddd9-4e70-9555-c6e81e05b347","timestamp":"2026-09-16T10:09:37.726377","source":"environment","parent_id":"85640bb2-c981-4093-8e5a-a7429a28be9d","key":"execution_status","value":"running","kind":"ConversationStateUpdateEvent"}},{"type":"durable","seq":4,"event":{"id":"de8f5622-4874-4036-8ff3-191eecc22e94","timestamp":"2026-09-16T10:09:37.728616","source":"environment","parent_id":"85640bb2-c981-4093-8e5a-a7429a28be9d","key":"stats","value":{"usage_to_metrics":{"agent":{"model_name":"openai/mock","accumulated_cost":0,"max_budget_per_task":null,"accumulated_token_usage":{"model":"openai/mock","prompt_tokens":1,"completion_tokens":1,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":2,"response_id":""}}}},"kind":"ConversationStateUpdateEvent"}},{"type":"item_started","item_id":"682e0082-a801-4e46-aefd-57133d568906","attempt":1,"anchor_seq":4},{"type":"delta","item_id":"682e0082-a801-4e46-aefd-57133d568906","attempt":1,"order":0,"kind":"text","content":"Let","chunk_id":"chatcmpl-e146aeac","choice_index":0},{"type":"delta","item_id":"682e0082-a801-4e46-aefd-57133d568906","attempt":1,"order":1,"kind":"text","content":" me","chunk_id":"chatcmpl-e146aeac","choice_index":0},{"type":"delta","item_id":"682e0082-a801-4e46-aefd-57133d568906","attempt":1,"order":2,"kind":"text","content":" check","chunk_id":"chatcmpl-e146aeac","choice_index":0},{"type":"delta","item_id":"682e0082-a801-4e46-aefd-57133d568906","attempt":1,"order":3,"kind":"text","content":" the","chunk_id":"chatcmpl-e146aeac","choice_index":0}],"resumeAfterSeq":4,"after":[{"type":"sync","from_seq":4,"through_seq":4},{"type":"transient","event":{"id":"cc6477ad-fd81-4dbb-a197-86d4b5d80238","timestamp":"2026-09-16T10:09:38.873285","source":"environment","key":"full_state","value":{"id":"52e2857d-fdb3-423b-88a8-3e02ac37abb0","agent":{"llm":{"model":"openai/mock","api_key":"**********","auth_type":"api_key","base_url":"http://127.0.0.1:28100/v1","openrouter_site_url":"https://docs.all-hands.dev/","openrouter_app_name":"OpenHands","num_retries":5,"retry_multiplier":8,"retry_min_wait":8,"retry_max_wait":64,"timeout":300,"max_message_chars":30000,"api_mode":"auto","capability_overrides":{},"stream":true,"drop_params":true,"modify_params":true,"disable_stop_word":false,"caching_prompt":true,"log_completions":false,"log_completions_folder":"logs/completions","native_tool_calling":true,"reasoning_effort":"high","enable_encrypted_reasoning":true,"prompt_cache_retention":"24h","extended_thinking_budget":200000,"usage_id":"agent","litellm_extra_body":{},"is_subscription":false},"tools":[{"name":"terminal","params":{}}],"mcp_config":{},"include_default_tools":["FinishTool","ThinkTool"],"system_prompt_filename":"system_prompt.j2","security_policy_filename":"security_policy.j2","system_prompt_kwargs":{"llm_security_analyzer":true},"tool_concurrency_limit":1,"kind":"Agent"},"workspace":{"working_dir":"/workspace/project","kind":"LocalWorkspace"},"persistence_dir":"workspace/conversations/52e2857dfdb3423b88a83e02ac37abb0","max_iterations":500,"stuck_detection":true,"execution_status":"running","confirmation_policy":{"kind":"NeverConfirm"},"activated_knowledge_skills":[],"activated_path_rules":[],"invoked_skills":[],"blocked_actions":{},"blocked_messages":{},"last_user_message_id":"85640bb2-c981-4093-8e5a-a7429a28be9d","leaf_event_id":"85640bb2-c981-4093-8e5a-a7429a28be9d","head_is_empty":false,"stats":{"usage_to_metrics":{"agent":{"model_name":"openai/mock","accumulated_cost":0,"accumulated_token_usage":{"model":"openai/mock","prompt_tokens":1,"completion_tokens":1,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":2,"response_id":""},"costs":[],"response_latencies":[{"model":"openai/mock","latency":0.00786280632019043,"response_id":"x"}],"token_usages":[{"model":"openai/mock","prompt_tokens":1,"completion_tokens":1,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":2,"response_id":"x"}]}}},"secret_registry":{"secret_sources":{}},"tags":{},"agent_state":{}},"kind":"ConversationStateUpdateEvent"}},{"type":"delta","item_id":"682e0082-a801-4e46-aefd-57133d568906","attempt":1,"order":10,"kind":"text","content":" files","chunk_id":"chatcmpl-e146aeac","choice_index":0},{"type":"delta","item_id":"682e0082-a801-4e46-aefd-57133d568906","attempt":1,"order":11,"kind":"text","content":" are","chunk_id":"chatcmpl-e146aeac","choice_index":0},{"type":"delta","item_id":"682e0082-a801-4e46-aefd-57133d568906","attempt":1,"order":12,"kind":"text","content":" there","chunk_id":"chatcmpl-e146aeac","choice_index":0},{"type":"delta","item_id":"682e0082-a801-4e46-aefd-57133d568906","attempt":1,"order":13,"kind":"text","content":" before","chunk_id":"chatcmpl-e146aeac","choice_index":0},{"type":"delta","item_id":"682e0082-a801-4e46-aefd-57133d568906","attempt":1,"order":14,"kind":"text","content":" answering","chunk_id":"chatcmpl-e146aeac","choice_index":0},{"type":"delta","item_id":"682e0082-a801-4e46-aefd-57133d568906","attempt":1,"order":15,"kind":"text","content":" you","chunk_id":"chatcmpl-e146aeac","choice_index":0},{"type":"delta","item_id":"682e0082-a801-4e46-aefd-57133d568906","attempt":1,"order":16,"kind":"text","content":" properly.","chunk_id":"chatcmpl-e146aeac","choice_index":0},{"type":"durable","seq":5,"event":{"id":"682e0082-a801-4e46-aefd-57133d568906","timestamp":"2026-09-16T10:09:39.850964","source":"agent","parent_id":"85640bb2-c981-4093-8e5a-a7429a28be9d","thought":[{"cache_prompt":false,"type":"text","text":"Let me check the workspace first so I know what files are there before answering you properly."}],"thinking_blocks":[],"action":{"command":"ls","is_input":false,"reset":false,"kind":"TerminalAction"},"tool_name":"terminal","tool_call_id":"call_7f8662","tool_call":{"id":"call_7f8662","name":"terminal","arguments":"{\"command\": \"ls\"}","origin":"completion"},"llm_response_id":"chatcmpl-e146aeac","security_risk":"UNKNOWN","summary":"terminal: {\"command\": \"ls\"}","kind":"ActionEvent"}},{"type":"durable","seq":6,"event":{"id":"0bd5b460-2847-458d-8969-ccb7bf75fed5","timestamp":"2026-09-16T10:09:40.455950","source":"environment","parent_id":"682e0082-a801-4e46-aefd-57133d568906","tool_name":"terminal","tool_call_id":"call_7f8662","observation":{"content":[{"cache_prompt":false,"type":"text","text":""}],"is_error":false,"command":"ls","exit_code":0,"timeout":false,"metadata":{"exit_code":0,"pid":-1,"username":"user","hostname":"Vascos-MacBook-Pro","working_dir":"/workspace/project","py_interpreter_path":"/opt/agent-server/bin/python","prefix":"","suffix":"\n[The command completed with exit code 0.]"},"kind":"TerminalObservation"},"action_id":"682e0082-a801-4e46-aefd-57133d568906","extended_content":[],"kind":"ObservationEvent"}},{"type":"durable","seq":7,"event":{"id":"2a55d20d-3b8d-4b33-89c3-1a8a681394f4","timestamp":"2026-09-16T10:09:39.850368","source":"environment","parent_id":"0bd5b460-2847-458d-8969-ccb7bf75fed5","key":"stats","value":{"usage_to_metrics":{"agent":{"model_name":"openai/mock","accumulated_cost":0,"max_budget_per_task":null,"accumulated_token_usage":{"model":"openai/mock","prompt_tokens":3238,"completion_tokens":49,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":3285,"response_id":""}}}},"kind":"ConversationStateUpdateEvent"}},{"type":"item_started","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"anchor_seq":7},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":0,"kind":"text","content":"All","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":1,"kind":"text","content":" done.","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":2,"kind":"text","content":" The","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":3,"kind":"text","content":" workspace","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":4,"kind":"text","content":" looks","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":5,"kind":"text","content":" healthy","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":6,"kind":"text","content":" and","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":7,"kind":"text","content":" I","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":8,"kind":"text","content":" found","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":9,"kind":"text","content":" nothing","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":10,"kind":"text","content":" unusual","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":11,"kind":"text","content":" in","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":12,"kind":"text","content":" the","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":13,"kind":"text","content":" files","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":14,"kind":"text","content":" I","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":15,"kind":"text","content":" inspected","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":16,"kind":"text","content":" just","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"delta","item_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","attempt":1,"order":17,"kind":"text","content":" now.","chunk_id":"chatcmpl-c6b214e9","choice_index":0},{"type":"durable","seq":8,"event":{"id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","timestamp":"2026-09-16T10:09:42.720807","source":"agent","parent_id":"0bd5b460-2847-458d-8969-ccb7bf75fed5","llm_message":{"role":"assistant","content":[{"cache_prompt":false,"type":"text","text":"All done. The workspace looks healthy and I found nothing unusual in the files I inspected just now."}],"thinking_blocks":[]},"llm_response_id":"chatcmpl-c6b214e9","activated_skills":[],"extended_content":[],"kind":"MessageEvent"}},{"type":"durable","seq":9,"event":{"id":"044b2580-a82a-4ff9-96df-7c6eadec7371","timestamp":"2026-09-16T10:09:42.724003","source":"environment","parent_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","key":"execution_status","value":"finished","kind":"ConversationStateUpdateEvent"}},{"type":"durable","seq":10,"event":{"id":"bec60ac9-eed1-43ca-98e0-79a3ec2e42c2","timestamp":"2026-09-16T10:09:42.720342","source":"environment","parent_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","key":"stats","value":{"usage_to_metrics":{"agent":{"model_name":"openai/mock","accumulated_cost":0,"max_budget_per_task":null,"accumulated_token_usage":{"model":"openai/mock","prompt_tokens":6600,"completion_tokens":69,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":3382,"response_id":""}}}},"kind":"ConversationStateUpdateEvent"}},{"type":"transient","event":{"id":"94538dce-0a3a-455c-8fce-2ead560d9991","timestamp":"2026-09-16T10:09:42.731143","source":"environment","key":"full_state","value":{"id":"52e2857d-fdb3-423b-88a8-3e02ac37abb0","agent":{"llm":{"model":"openai/mock","api_key":"**********","auth_type":"api_key","base_url":"http://127.0.0.1:28100/v1","openrouter_site_url":"https://docs.all-hands.dev/","openrouter_app_name":"OpenHands","num_retries":5,"retry_multiplier":8,"retry_min_wait":8,"retry_max_wait":64,"timeout":300,"max_message_chars":30000,"api_mode":"auto","capability_overrides":{},"stream":true,"drop_params":true,"modify_params":true,"disable_stop_word":false,"caching_prompt":true,"log_completions":false,"log_completions_folder":"logs/completions","native_tool_calling":true,"reasoning_effort":"high","enable_encrypted_reasoning":true,"prompt_cache_retention":"24h","extended_thinking_budget":200000,"usage_id":"agent","litellm_extra_body":{},"is_subscription":false},"tools":[{"name":"terminal","params":{}}],"mcp_config":{},"include_default_tools":["FinishTool","ThinkTool"],"system_prompt_filename":"system_prompt.j2","security_policy_filename":"security_policy.j2","system_prompt_kwargs":{"llm_security_analyzer":true},"tool_concurrency_limit":1,"kind":"Agent"},"workspace":{"working_dir":"/workspace/project","kind":"LocalWorkspace"},"persistence_dir":"workspace/conversations/52e2857dfdb3423b88a83e02ac37abb0","max_iterations":500,"stuck_detection":true,"execution_status":"finished","confirmation_policy":{"kind":"NeverConfirm"},"activated_knowledge_skills":[],"activated_path_rules":[],"invoked_skills":[],"blocked_actions":{},"blocked_messages":{},"last_user_message_id":"85640bb2-c981-4093-8e5a-a7429a28be9d","leaf_event_id":"0e7e9aa9-4296-47f5-bd8f-bbbe3a49e013","head_is_empty":false,"stats":{"usage_to_metrics":{"agent":{"model_name":"openai/mock","accumulated_cost":0,"accumulated_token_usage":{"model":"openai/mock","prompt_tokens":6600,"completion_tokens":69,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":3382,"response_id":""},"costs":[],"response_latencies":[{"model":"openai/mock","latency":0.00786280632019043,"response_id":"x"},{"model":"openai/mock","latency":2.1143009662628174,"response_id":"chatcmpl-e146aeac"},{"model":"openai/mock","latency":2.2532763481140137,"response_id":"chatcmpl-c6b214e9"}],"token_usages":[{"model":"openai/mock","prompt_tokens":1,"completion_tokens":1,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":2,"response_id":"x"},{"model":"openai/mock","prompt_tokens":3237,"completion_tokens":48,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":3285,"response_id":"chatcmpl-e146aeac"},{"model":"openai/mock","prompt_tokens":3362,"completion_tokens":20,"cache_read_tokens":0,"cache_write_tokens":0,"reasoning_tokens":0,"context_window":0,"per_turn_token":3382,"response_id":"chatcmpl-c6b214e9"}]}}},"secret_registry":{"secret_sources":{}},"tags":{},"agent_state":{}},"kind":"ConversationStateUpdateEvent"}}]}\ No newline at end of filediff --git a/__tests__/helpers/msw-websocket-setup.ts b/__tests__/helpers/msw-websocket-setup.tsindex 114903e91a..25d533e1bb 100644--- a/__tests__/helpers/msw-websocket-setup.ts+++ b/__tests__/helpers/msw-websocket-setup.ts@@ -37,8 +37,8 @@ export const createWebSocketTestSetup = (/*** Standard WebSocket test setup for conversation WebSocket handler tests- * Updated to use the V1 WebSocket URL pattern: /sockets/events/{conversationId}+ * Updated to use the V1 WebSocket URL pattern: /sockets/session/{conversationId}* Uses a wildcard pattern to match any conversation ID*/export const conversationWebSocketTestSetup = () =>- createWebSocketTestSetup("ws://localhost:3000/sockets/events/*");+ createWebSocketTestSetup("ws://localhost:3000/sockets/session/*");diff --git a/__tests__/hooks/query/use-backends-health.test.tsx b/__tests__/hooks/query/use-backends-health.test.tsxindex f755a645a7..0794b670e0 100644--- a/__tests__/hooks/query/use-backends-health.test.tsx+++ b/__tests__/hooks/query/use-backends-health.test.tsx@@ -68,7 +68,7 @@ function wrapper({ children }: { children: React.ReactNode }) {beforeEach(() => {getSettingsMock.mockReset();getServerInfoMock.mockReset();- getServerInfoMock.mockResolvedValue({ version: "1.28.0" });+ getServerInfoMock.mockResolvedValue({ version: "1.48.0" });getCurrentCloudApiKeyMock.mockReset();getCloudOrganizationsMock.mockReset();vi.mocked(ServerClient).mockClear();@@ -112,7 +112,7 @@ describe("useBackendsHealth", () => {expect(result.current[localBackend.id]).toMatchObject({isConnected: false,lastError:- "Agent Canvas requires agent-server 1.28.0 or newer; this backend is running 1.27.1. Please upgrade the agent-server backend.",+ "Agent Canvas requires agent-server 1.47.0 or newer; this backend is running 1.27.1. Please upgrade the agent-server backend.",}),// Failing probes now retry a couple of times before settling.{ timeout: 3000 },diff --git a/__tests__/hooks/query/use-conversation-history.test.tsx b/__tests__/hooks/query/use-conversation-history.test.tsxindex 39b5810a8e..1806e22b40 100644--- a/__tests__/hooks/query/use-conversation-history.test.tsx+++ b/__tests__/hooks/query/use-conversation-history.test.tsx@@ -458,4 +458,63 @@ describe("useConversationHistory cache key stability", () => {expect(queries).toHaveLength(1);expect(queries[0].options.gcTime).toBeGreaterThanOrEqual(30 * 60 * 1000);});++ describe("session-socket resume cursor (afterSeq)", () => {+ const withUrl = () =>+ vi.mocked(useUserConversation).mockReturnValue({+ data: {+ ...makeConversation("V1"),+ conversation_url: "http://localhost:18000/api/conversations/conv-seq",+ },+ isLoading: false,+ isPending: false,+ isError: false,+ error: null,+ refetch: vi.fn(),+ } as any);++ it("derives afterSeq from the count read before the page", async () => {+ withUrl();+ const calls: string[] = [];+ vi.spyOn(EventService, "getEventCount").mockImplementation(async () => {+ calls.push("count");+ return 120;+ });+ vi.spyOn(EventService, "searchEvents").mockImplementation(async () => {+ calls.push("search");+ return makePage([makeEvent()]);+ });++ const { result } = renderHook(() => useConversationHistory("conv-seq"), {+ wrapper,+ });+ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ // Count first: anything appended between the two reads has+ // seq >= count, so it is replayed rather than skipped.+ expect(calls).toEqual(["count", "search"]);+ expect(result.current.data?.afterSeq).toBe(119);+ });++ it("still loads the page, without a cursor, when the count fails", async () => {+ withUrl();+ vi.spyOn(EventService, "getEventCount").mockRejectedValue(+ new Error("boom"),+ );+ vi.spyOn(EventService, "searchEvents").mockResolvedValue(+ makePage([makeEvent("evt-a")]),+ );++ const { result } = renderHook(+ () => useConversationHistory("conv-seq-2"),+ {+ wrapper,+ },+ );+ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ expect(result.current.data?.events).toHaveLength(1);+ expect(result.current.data?.afterSeq).toBeNull();+ });+ });});diff --git a/__tests__/hooks/use-streamed-text.test.tsx b/__tests__/hooks/use-streamed-text.test.tsxnew file mode 100644index 0000000000..3560215e78--- /dev/null+++ b/__tests__/hooks/use-streamed-text.test.tsx@@ -0,0 +1,95 @@+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";+import { act, renderHook } from "@testing-library/react";+import { useStreamedText } from "#/hooks/use-streamed-text";++/** Drive `requestAnimationFrame` by hand so the reveal cadence is explicit. */+function manualFrames() {+ let now = 0;+ const callbacks = new Map<number, FrameRequestCallback>();+ let nextHandle = 1;++ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {+ const handle = nextHandle;+ nextHandle += 1;+ callbacks.set(handle, callback);+ return handle;+ });+ vi.stubGlobal("cancelAnimationFrame", (handle: number) => {+ callbacks.delete(handle);+ });++ return {+ /** Advance one 16ms frame. */+ tick: (steps = 1) => {+ for (let i = 0; i < steps; i += 1) {+ now += 16;+ const scheduled = [...callbacks.values()];+ callbacks.clear();+ act(() => {+ scheduled.forEach((callback) => callback(now));+ });+ }+ },+ pending: () => callbacks.size,+ };+}++describe("useStreamedText", () => {+ let frames: ReturnType<typeof manualFrames>;++ beforeEach(() => {+ frames = manualFrames();+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("shows the initial text immediately", () => {+ const { result } = renderHook(() => useStreamedText("already here"));+ expect(result.current).toBe("already here");+ });++ it("reveals appended text over frames instead of all at once", () => {+ const { result, rerender } = renderHook(+ ({ text }) => useStreamedText(text),+ { initialProps: { text: "Hi" } },+ );++ rerender({ text: `Hi${"x".repeat(200)}` });+ // Not committed on arrival β the clock has not ticked yet.+ expect(result.current).toBe("Hi");++ frames.tick();+ expect(result.current.length).toBeGreaterThan("Hi".length);+ expect(result.current.length).toBeLessThan(202);++ // It still catches up: the backlog drains within a short window.+ frames.tick(40);+ expect(result.current).toBe(`Hi${"x".repeat(200)}`);+ expect(frames.pending()).toBe(0);+ });++ it("snaps when the text is not an extension of what is shown", () => {+ const { result, rerender } = renderHook(+ ({ text }) => useStreamedText(text),+ { initialProps: { text: "first attempt" } },+ );++ // A higher attempt supersedes the slot; re-typing it would be wrong.+ rerender({ text: "a completely different retry" });+ expect(result.current).toBe("a completely different retry");+ });++ it("cancels the pending frame on unmount", () => {+ const { rerender, unmount } = renderHook(+ ({ text }) => useStreamedText(text),+ { initialProps: { text: "a" } },+ );+ rerender({ text: `a${"b".repeat(50)}` });+ expect(frames.pending()).toBe(1);++ unmount();+ expect(frames.pending()).toBe(0);+ });+});diff --git a/__tests__/root.test.tsx b/__tests__/root.test.tsxindex aaa6f8fef9..8f2d7585a7 100644--- a/__tests__/root.test.tsx+++ b/__tests__/root.test.tsx@@ -210,7 +210,7 @@ describe("App root agent-server availability guard", () => {it("lets root-level onboarding navigate to the launched conversation before closing", async () => {server.use(http.get("*/server_info", () =>- HttpResponse.json({ uptime: 0, idle_time: 0, version: "1.28.1" }),+ HttpResponse.json({ uptime: 0, idle_time: 0, version: "1.48.0" }),),);@@ -359,7 +359,7 @@ describe("App root agent-server availability guard", () => {}),),http.get("*/server_info", () =>- HttpResponse.json({ uptime: 0, idle_time: 0, version: "1.28.1" }),+ HttpResponse.json({ uptime: 0, idle_time: 0, version: "1.48.0" }),),);@@ -415,7 +415,7 @@ describe("App root agent-server availability guard", () => {}),),http.get("*/server_info", () =>- HttpResponse.json({ uptime: 0, idle_time: 0, version: "1.28.1" }),+ HttpResponse.json({ uptime: 0, idle_time: 0, version: "1.48.0" }),),);@@ -681,7 +681,7 @@ describe("App root agent-server availability guard", () => {}),),http.get("*/server_info", () =>- HttpResponse.json({ uptime: 0, idle_time: 0, version: "1.28.1" }),+ HttpResponse.json({ uptime: 0, idle_time: 0, version: "1.48.0" }),),);diff --git a/__tests__/scripts/ingress.test.ts b/__tests__/scripts/ingress.test.tsindex 4d4004886e..e82ba2d40b 100644--- a/__tests__/scripts/ingress.test.ts+++ b/__tests__/scripts/ingress.test.ts@@ -424,7 +424,7 @@ describe("ingress proxy functionality", () => {it("adds runtime_services to proxied /server_info", async () => {const serverInfoBackend = createServer((_req, res) => {res.writeHead(200, { "Content-Type": "application/json" });- res.end(JSON.stringify({ version: "1.28.0" }));+ res.end(JSON.stringify({ version: "1.48.0" }));});const serverInfoBackendPort = await listenOnLoopback(serverInfoBackend);const runtimeIngressPort = await getFreePort();@@ -464,7 +464,7 @@ describe("ingress proxy functionality", () => {};expect(response.status).toBe(200);- expect(body.version).toBe("1.28.0");+ expect(body.version).toBe("1.48.0");expect(body.runtime_services).toEqual(JSON.parse(runtimeServicesInfo));} finally {await stopChild(runtimeIngress);diff --git a/__tests__/scripts/static-server.test.ts b/__tests__/scripts/static-server.test.tsindex f8e9d001a9..c05386782d 100644--- a/__tests__/scripts/static-server.test.ts+++ b/__tests__/scripts/static-server.test.ts@@ -416,7 +416,7 @@ describe("static-server.mjs", () => {const upstreamOrigin = await startHttpServer(createServer((_req, res) => {res.writeHead(200, { "Content-Type": "application/json" });- res.end(JSON.stringify({ version: "1.28.0" }));+ res.end(JSON.stringify({ version: "1.48.0" }));}),);const runtimeServicesInfo = JSON.stringify({@@ -445,7 +445,7 @@ describe("static-server.mjs", () => {};expect(response.status).toBe(200);- expect(body.version).toBe("1.28.0");+ expect(body.version).toBe("1.48.0");expect(body.runtime_services).toEqual(JSON.parse(runtimeServicesInfo));});diff --git a/__tests__/stores/use-event-store.test.ts b/__tests__/stores/use-event-store.test.tsindex 09fe92c65c..d82fc66db4 100644--- a/__tests__/stores/use-event-store.test.ts+++ b/__tests__/stores/use-event-store.test.ts@@ -75,17 +75,15 @@ const mockObservationEvent: ObservationEvent = {action_id: "test-action-1",};-const makeStreamingDeltaEvent = (- id: string,- content: string,-): StreamingDeltaEvent => ({- id,- timestamp: `2024-03-01T00:00:0${id.at(-1) ?? "0"}Z`,+const mockAgentMessageEvent: MessageEvent = {+ ...mockUserMessageEvent,+ id: "test-agent-message-1",source: "agent",- kind: "StreamingDeltaEvent",- content,- reasoning_content: null,-});+ llm_message: {+ role: "assistant",+ content: [{ type: "text", text: "partial text, finished" }],+ },+};const makeUserMessageEvent = (id: string, timestamp: string): MessageEvent => ({...mockUserMessageEvent,@@ -156,89 +154,86 @@ describe("useEventStore", () => {expect(result.current.events).toHaveLength(2);});- it("should compact consecutive streaming deltas in the raw event store", () => {+ it("keeps streaming slots out of the durable event log and eventIds", () => {const { result } = renderHook(() => useEventStore());- const first = makeStreamingDeltaEvent("delta-1", "hello ");- const second = makeStreamingDeltaEvent("delta-2", "world");act(() => {- result.current.addEvent(first);- result.current.addEvent(second);+ result.current.addEvent(mockUserMessageEvent);+ result.current.openStreamingSlot({+ type: "item_started",+ item_id: "item-1",+ });+ for (let i = 0; i < 1000; i += 1) {+ result.current.appendStreamingDeltas([+ {+ type: "delta",+ item_id: "item-1",+ attempt: 1,+ order: i,+ content: "x",+ },+ ]);+ }});- expect(result.current.events).toEqual([- {- ...first,- content: "hello world",- },- ]);- expect(result.current.uiEvents).toEqual([- {- ...first,- content: "hello world",- },- ]);- // Transient deltas are never tracked in `eventIds` β copying that Set once- // per token would otherwise be O(n^2).- expect(result.current.eventIds.has("delta-1")).toBe(false);- expect(result.current.eventIds.has("delta-2")).toBe(false);+ // The slot renders, but `events` and `eventIds` only ever hold durable+ // records β the slot's id IS the coming message's id, so tracking it would+ // dedupe the real message away.+ expect(result.current.events).toEqual([mockUserMessageEvent]);+ expect(result.current.eventIds.size).toBe(1);+ expect(result.current.uiEvents).toHaveLength(2);+ expect(+ (result.current.uiEvents[1] as StreamingDeltaEvent).content,+ ).toHaveLength(1000);});- it("should compact streaming deltas during bulk add", () => {+ it("retires a slot when the durable event with its id arrives", () => {const { result } = renderHook(() => useEventStore());- const first = makeStreamingDeltaEvent("delta-1", "hello ");- const second = makeStreamingDeltaEvent("delta-2", "world");act(() => {- result.current.addEvents([first, second]);+ result.current.openStreamingSlot({+ type: "item_started",+ item_id: mockAgentMessageEvent.id,+ });+ result.current.appendStreamingDeltas([+ {+ type: "delta",+ item_id: mockAgentMessageEvent.id,+ attempt: 1,+ order: 0,+ content: "partial",+ },+ ]);+ result.current.addEvent(mockAgentMessageEvent);});- expect(result.current.events).toHaveLength(1);- expect(result.current.events[0]).toMatchObject({- id: "delta-1",- content: "hello world",- });- // Transient deltas are never tracked in `eventIds`.- expect(result.current.eventIds.has("delta-1")).toBe(false);- expect(result.current.eventIds.has("delta-2")).toBe(false);+ expect(result.current.uiEvents).toEqual([mockAgentMessageEvent]);+ expect(result.current.events).toEqual([mockAgentMessageEvent]);});- it("should not grow eventIds with the raw streaming-delta count", () => {+ it("clears only the addressed socket's slots", () => {const { result } = renderHook(() => useEventStore());act(() => {- result.current.addEvent(mockUserMessageEvent);- for (let i = 0; i < 1000; i += 1) {- result.current.addEvent(makeStreamingDeltaEvent(`delta-${i}`, "x"));- }+ result.current.openStreamingSlot({+ type: "item_started",+ item_id: "main-item",+ });+ result.current.openStreamingSlot(+ { type: "item_started", item_id: "plan-item" },+ { isFromPlanningAgent: true },+ );+ result.current.clearStreamingSlots();});- // 1000 deltas collapse to a single event alongside the user message, and- // eventIds tracks only the durable user message β not the deltas. This is- // what keeps the per-token Set copy from going quadratic.- expect(result.current.events).toHaveLength(2);- expect(result.current.eventIds.size).toBe(1);- expect(result.current.eventIds.has(mockUserMessageEvent.id)).toBe(true);- expect(- (result.current.events[1] as StreamingDeltaEvent).content,- ).toHaveLength(1000);- });-- it("should not compact streaming deltas from different senders (#1656)", () => {- const { result } = renderHook(() => useEventStore());- const mainDelta = makeStreamingDeltaEvent("delta-1", "main ");- const planningDelta = {- ...makeStreamingDeltaEvent("delta-2", "planning"),- isFromPlanningAgent: true,- };+ expect(result.current.uiEvents.map((event) => event.id)).toEqual([+ "plan-item",+ ]);- // A planning-agent delta after a main-agent delta must not concatenate.act(() => {- result.current.addEvent(mainDelta);- result.current.addEvent(planningDelta);+ result.current.clearStreamingSlots(true);});-- expect(result.current.events).toEqual([mainDelta, planningDelta]);+ expect(result.current.uiEvents).toEqual([]);});it("should apply action-to-observation UI replacement during bulk add", () => {diff --git a/__tests__/utils/handle-event-for-ui.test.ts b/__tests__/utils/handle-event-for-ui.test.tsindex 42632be18b..63182b53d3 100644--- a/__tests__/utils/handle-event-for-ui.test.ts+++ b/__tests__/utils/handle-event-for-ui.test.ts@@ -8,7 +8,18 @@ import {} from "#/types/agent-server/core";import { ACPToolCallEvent } from "#/types/agent-server/core/events/acp-tool-call-event";import { StreamingDeltaEvent } from "#/types/agent-server/core/events/streaming-delta-event";-import { handleEventForUI } from "#/utils/handle-event-for-ui";+import type {+ DeltaFrame,+ ItemStartedFrame,+} from "#/types/agent-server/session-frames";+import { isStreamingDeltaEvent } from "#/types/agent-server/type-guards";+import {+ abortStreamingSlot,+ appendStreamingDeltas,+ clearStreamingSlots,+ handleEventForUI,+ openStreamingSlot,+} from "#/utils/handle-event-for-ui";describe("handleEventForUI", () => {const mockObservationEvent: ObservationEvent = {@@ -292,358 +303,291 @@ describe("handleEventForUI", () => {});});- describe("StreamingDeltaEvent", () => {- it("merges consecutive deltas into a single provisional assistant event", () => {- const first = makeStreamingDelta("delta-1", "I'll start ");- const second = makeStreamingDelta("delta-2", "working on that.");-- const afterFirst = handleEventForUI(first, [mockMessageEvent]);- const afterSecond = handleEventForUI(second, afterFirst);-- expect(afterSecond).toEqual([- mockMessageEvent,- {- ...first,- content: "I'll start working on that.",- reasoning_content: null,- },- ]);- });+ describe("streaming slots", () => {+ const started = (+ itemId: string,+ extra: Partial<ItemStartedFrame> = {},+ ): ItemStartedFrame => ({+ type: "item_started",+ item_id: itemId,+ attempt: 1,+ ...extra,+ });++ const delta = (+ itemId: string,+ content: string,+ extra: Partial<DeltaFrame> = {},+ ): DeltaFrame => ({+ type: "delta",+ item_id: itemId,+ attempt: 1,+ order: 0,+ kind: "text",+ content,+ ...extra,+ });++ const slotsOf = (events: OpenHandsEvent[]) =>+ events.filter((event): event is StreamingDeltaEvent =>+ isStreamingDeltaEvent(event),+ );- it("keeps the canonical finish event after streamed content", () => {- const first = makeStreamingDelta("delta-1", "I'll start ");- const second = makeStreamingDelta("delta-2", "working on that.");- const streamedDelta = handleEventForUI(- second,- handleEventForUI(first, []),- ).at(-1)!;- const uiEvents = [mockMessageEvent, streamedDelta];+ it("opens a slot keyed by item_id and accumulates its deltas", () => {+ const opened = openStreamingSlot(started("item-1"), [mockMessageEvent]);+ const result = appendStreamingDeltas(+ [delta("item-1", "I'll start "), delta("item-1", "working on that.")],+ opened,+ );- const result = handleEventForUI(mockFinishActionEvent, uiEvents);+ expect(slotsOf(result)).toHaveLength(1);+ expect(slotsOf(result)[0]).toMatchObject({+ id: "item-1",+ content: "I'll start working on that.",+ reasoning_content: null,+ });+ });++ it("routes reasoning deltas to reasoning_content, independently of text", () => {+ const opened = openStreamingSlot(started("item-1"), []);+ const result = appendStreamingDeltas(+ [+ delta("item-1", "thinking", { kind: "reasoning" }),+ delta("item-1", "answer"),+ delta("item-1", " more", { kind: "reasoning" }),+ ],+ opened,+ );- expect(result).toEqual([mockMessageEvent, mockFinishActionEvent]);- expect(result.at(-1)).toBe(mockFinishActionEvent);+ expect(slotsOf(result)[0]).toMatchObject({+ content: "answer",+ reasoning_content: "thinking more",+ });});- it("keeps the canonical agent message after streamed content", () => {- const first = makeStreamingDelta("delta-1", "I'll start ");- const second = makeStreamingDelta("delta-2", "working on that.");- const streamedDelta = handleEventForUI(- second,- handleEventForUI(first, []),- ).at(-1)!;- const uiEvents = [mockMessageEvent, streamedDelta];+ it("retires the slot when the durable event carries its id", () => {+ const opened = openStreamingSlot(started("test-agent-message-1"), [+ mockMessageEvent,+ ]);+ const streamed = appendStreamingDeltas(+ [delta("test-agent-message-1", "partial text")],+ opened,+ );- const result = handleEventForUI(mockAgentMessageEvent, uiEvents);+ const result = handleEventForUI(mockAgentMessageEvent, streamed);+ // One equality test on the id β the streamed text is never compared.expect(result).toEqual([mockMessageEvent, mockAgentMessageEvent]);- expect(result.at(-1)).toBe(mockAgentMessageEvent);});- it("replaces aggregated streamed content with the canonical final message", () => {- const first = makeStreamingDelta(- "delta-1",- "I'll start working on that.",+ it("retires the slot in place, keeping events that arrived beside it", () => {+ const opened = openStreamingSlot(+ started("test-agent-message-1", { anchor_seq: 0 }),+ [{ ...mockMessageEvent, seq: 0 }],);- const second = makeStreamingDelta("delta-2", "I found the issue.");- const aggregateAgentMessage: MessageEvent = {- ...mockAgentMessageEvent,- llm_message: {- role: "assistant",- content: [- {- type: "text",- text: "I'll start working on that.I found the issue.",- },- ],- },- };-- const afterFirst = handleEventForUI(first, [mockMessageEvent]);- const afterObservation = handleEventForUI(- mockObservationEvent,- afterFirst,+ const streamed = appendStreamingDeltas(+ [delta("test-agent-message-1", "partial")],+ opened,+ );+ // A user message lands mid-stream, sequenced after the slot's anchor.+ const interrupted = handleEventForUI(+ { ...mockMessageEvent, id: "mid-stream", seq: 1 },+ streamed,);- const afterSecond = handleEventForUI(second, afterObservation);- const result = handleEventForUI(aggregateAgentMessage, afterSecond);- expect(result).toEqual([- mockMessageEvent,- mockObservationEvent,- aggregateAgentMessage,+ const result = handleEventForUI(mockAgentMessageEvent, interrupted);++ expect(result.map((event) => event.id)).toEqual([+ mockMessageEvent.id,+ mockAgentMessageEvent.id,+ "mid-stream",]);});- it("uses canonical final content while retaining reasoning-only deltas", () => {- const contentDelta = makeStreamingDelta(- "delta-content",- "I'll start working on that.",+ it("keeps a mid-stream event below the slot rather than splitting it (#15433)", () => {+ const opened = openStreamingSlot(started("item-1", { anchor_seq: 0 }), [+ { ...mockMessageEvent, seq: 0 },+ ]);+ const firstHalf = appendStreamingDeltas(+ [delta("item-1", "first half")],+ opened,+ );+ const interrupted = handleEventForUI(+ { ...mockMessageEvent, id: "mid-stream", seq: 1 },+ firstHalf,+ );+ const result = appendStreamingDeltas(+ [delta("item-1", " second half")],+ interrupted,);- const reasoningDelta: StreamingDeltaEvent = {- id: "delta-reasoning",- kind: "StreamingDeltaEvent",- timestamp: Date.now().toString(),- source: "agent",- content: null,- reasoning_content: "thinking...",- };- const finalMessage: MessageEvent = {- ...mockAgentMessageEvent,- llm_message: {- role: "assistant",- content: [- {- type: "text",- text: "I'll start working on that. Done.",- },- ],- },- };- const result = handleEventForUI(finalMessage, [- mockMessageEvent,- contentDelta,- mockObservationEvent,- reasoningDelta,- ]);-- expect(result).toEqual([- mockMessageEvent,- mockObservationEvent,- reasoningDelta,- finalMessage,+ // One slot, still whole, still above the interrupting message.+ expect(slotsOf(result)).toHaveLength(1);+ expect(slotsOf(result)[0].content).toBe("first half second half");+ expect(result.map((event) => event.id)).toEqual([+ mockMessageEvent.id,+ "item-1",+ "mid-stream",]);});- it("keeps the canonical final message after leading streamed whitespace", () => {- const streamedDelta = makeStreamingDelta(- "delta-1",- "\nI'll start working on that. Done.",- );+ it("supersedes the slot's text when a higher attempt streams it again", () => {+ const opened = openStreamingSlot(started("item-1"), []);+ const first = appendStreamingDeltas([delta("item-1", "retried")], opened);- const result = handleEventForUI(mockAgentMessageEvent, [- mockMessageEvent,- streamedDelta,- ]);+ const reopened = openStreamingSlot(+ started("item-1", { attempt: 2 }),+ first,+ );+ expect(slotsOf(reopened)[0].content).toBeNull();- expect(result).toEqual([mockMessageEvent, mockAgentMessageEvent]);- expect(result.at(-1)).toBe(mockAgentMessageEvent);+ const result = appendStreamingDeltas(+ [delta("item-1", "fresh text", { attempt: 2 })],+ reopened,+ );+ expect(slotsOf(result)).toHaveLength(1);+ expect(slotsOf(result)[0].content).toBe("fresh text");});- it("replaces unmatched streamed text with the canonical final message", () => {- const streamedDelta = makeStreamingDelta(- "delta-1",- "I'll start working on that.",- );- const finalMessage: MessageEvent = {- ...mockAgentMessageEvent,- llm_message: {- role: "assistant",- content: [{ type: "text", text: "Done." }],- },- };+ it("keeps streamed text when the current attempt's start is repeated", () => {+ const opened = openStreamingSlot(started("item-1"), []);+ const streamed = appendStreamingDeltas([delta("item-1", "kept")], opened);- const result = handleEventForUI(finalMessage, [- mockMessageEvent,- streamedDelta,- ]);+ const result = openStreamingSlot(started("item-1"), streamed);- expect(result).toEqual([mockMessageEvent, finalMessage]);+ expect(result).toBe(streamed);+ expect(slotsOf(result)[0].content).toBe("kept");});- it("preserves streamed reasoning when the final message replaces unmatched text", () => {- const streamedDelta: StreamingDeltaEvent = {- ...makeStreamingDelta("delta-1", "Stale partial text"),- reasoning_content: "Reasoning available only in the stream",- };- const finalMessage: MessageEvent = {- ...mockAgentMessageEvent,- llm_message: {- role: "assistant",- content: [{ type: "text", text: "Canonical final text" }],- },- };+ it("places the slot by anchor_seq when a message lands before the first token", () => {+ // The SDK reads the anchor when the step opens, before the LLM call; a+ // user message persisted while waiting for the first token has a higher+ // seq and has already rendered by the time item_started arrives.+ const history = [+ { ...mockMessageEvent, seq: 0 },+ { ...mockMessageEvent, id: "sent-while-waiting", seq: 1 },+ ];- const result = handleEventForUI(finalMessage, [- mockMessageEvent,- streamedDelta,- ]);+ const result = openStreamingSlot(+ started("item-1", { anchor_seq: 0 }),+ history,+ );- expect(result).toEqual([- mockMessageEvent,- { ...streamedDelta, content: null },- finalMessage,+ expect(result.map((event) => event.id)).toEqual([+ mockMessageEvent.id,+ "item-1",+ "sent-while-waiting",]);+ // Borrowing the anchor's timestamp keeps it there through a re-sort.+ expect(slotsOf(result)[0].timestamp).toBe(mockMessageEvent.timestamp);});- it("drops streamed reasoning when the final message renders it inline", () => {- const streamedDelta: StreamingDeltaEvent = {- ...makeStreamingDelta("delta-1", "Canonical final text"),- reasoning_content: "Reasoning rendered by the final message",- };- const finalMessage: MessageEvent = {- ...mockAgentMessageEvent,- llm_message: {- role: "assistant",- content: [- {- type: "text",- text: "<think>Reasoning rendered by the final message</think>Canonical final text",- },- ],+ it("borrows the anchor event's timestamp, not its neighbour's", () => {+ const history = [+ {+ ...mockMessageEvent,+ timestamp: "2026-09-16T10:00:00.000001",+ seq: 4,},- };+ // e.g. a transient or client-stamped event with a different clock+ {+ ...mockMessageEvent,+ id: "no-seq",+ timestamp: "2026-09-16T23:59:59Z",+ },+ ];- const result = handleEventForUI(finalMessage, [- mockMessageEvent,- streamedDelta,- ]);+ const result = openStreamingSlot(+ started("item-1", { anchor_seq: 4 }),+ history,+ );- expect(result).toEqual([mockMessageEvent, finalMessage]);+ expect(slotsOf(result)[0].timestamp).toBe("2026-09-16T10:00:00.000001");});- it("keeps deltas from older turns when a later turn finishes", () => {- const oldUserMessage: MessageEvent = {- ...mockMessageEvent,- id: "old-user-message",- };- const nextUserMessage: MessageEvent = {- ...mockMessageEvent,- id: "next-user-message",- llm_message: {- role: "user",- content: [{ type: "text", text: "Next task" }],- },- };- const oldDelta = makeStreamingDelta("old-delta", "Old live text");- const currentDelta = makeStreamingDelta(- "current-delta",- "Current live text",- );-- const result = handleEventForUI(mockFinishActionEvent, [- oldUserMessage,- oldDelta,- nextUserMessage,- currentDelta,- ]);+ it("supersedes on a higher-attempt delta even without its item_started", () => {+ const opened = openStreamingSlot(started("item-1"), []);+ const first = appendStreamingDeltas([delta("item-1", "stale")], opened);- expect(result).toEqual([- oldUserMessage,- oldDelta,- nextUserMessage,- mockFinishActionEvent,- ]);- });+ const result = appendStreamingDeltas(+ [+ delta("item-1", "fresh", { attempt: 2 }),+ delta("item-1", "think", { attempt: 2, kind: "reasoning" }),+ ],+ first,+ );- it("appends final message normally when all deltas are reasoning-only", () => {- // When every streaming delta carries only reasoning_content (no content),- // streamingSegments is empty β finalizeStreamingDeltasInPlace returns null- // β finalEvent is appended after the delta as a regular message bubble.- const reasoningDelta: StreamingDeltaEvent = {- id: "delta-reasoning",- kind: "StreamingDeltaEvent",- timestamp: Date.now().toString(),- source: "agent",- content: null,- reasoning_content: "thinking...",- };- const result = handleEventForUI(mockAgentMessageEvent, [- mockMessageEvent,- reasoningDelta,- ]);- expect(result).toEqual([- mockMessageEvent,- reasoningDelta,- mockAgentMessageEvent,- ]);+ expect(slotsOf(result)[0]).toMatchObject({+ attempt: 2,+ content: "fresh",+ reasoning_content: "think",+ });});- it("does not merge deltas from different senders into one bubble (#1656)", () => {- // A planning-agent delta must not concatenate onto a main-agent delta;- // they stay separate bubbles.- const mainDelta = makeStreamingDelta("delta-main", "Main agent says ");- const planningDelta = {- ...makeStreamingDelta("delta-planning", "planning agent says"),- isFromPlanningAgent: true,- };-- const result = handleEventForUI(planningDelta, [- mockMessageEvent,- mainDelta,- ]);+ it("ignores frames from an attempt already superseded", () => {+ const opened = openStreamingSlot(started("item-1", { attempt: 2 }), []);+ const result = appendStreamingDeltas(+ [delta("item-1", "stale", { attempt: 1 })],+ opened,+ );- expect(result).toEqual([mockMessageEvent, mainDelta, planningDelta]);+ expect(slotsOf(result)[0].content).toBeNull();+ expect(openStreamingSlot(started("item-1", { attempt: 1 }), opened)).toBe(+ opened,+ );});- it("still merges consecutive deltas from the same sender", () => {- const first = {- ...makeStreamingDelta("delta-1", "planning "),- isFromPlanningAgent: true,- };- const second = {- ...makeStreamingDelta("delta-2", "continues"),+ it("opens a slot for a live delta whose item_started predates the connection", () => {+ const result = appendStreamingDeltas(+ [delta("item-late", "streamed after connect")],+ [mockMessageEvent],+ { isFromPlanningAgent: true },+ );++ expect(slotsOf(result)).toHaveLength(1);+ expect(slotsOf(result)[0]).toMatchObject({+ id: "item-late",+ content: "streamed after connect",isFromPlanningAgent: true,- };+ });+ });- const result = handleEventForUI(second, [mockMessageEvent, first]);+ it("does not reopen an item whose durable event already arrived", () => {+ const result = appendStreamingDeltas(+ [delta("test-agent-message-1", "straggler")],+ [mockMessageEvent, mockAgentMessageEvent],+ { isFinished: (itemId) => itemId === mockAgentMessageEvent.id },+ );- expect(result).toEqual([- mockMessageEvent,- { ...first, content: "planning continues", reasoning_content: null },- ]);+ expect(slotsOf(result)).toHaveLength(0);});- it("planning final preserves a still-live main-agent delta (#1656)", () => {- // Main and planning sockets share this event store. A planning-agent- // final must supersede only the planning stream; the main agent's live- // delta must survive.- const mainDelta = makeStreamingDelta("delta-main", "Main still typing");- const planningDelta = {- ...makeStreamingDelta("delta-planning", "Planning says hello"),- isFromPlanningAgent: true,- };- const planningFinal = {- ...mockAgentMessageEvent,- id: "planning-final",- isFromPlanningAgent: true,- llm_message: {- role: "assistant" as const,- content: [{ type: "text" as const, text: "Planning says hello" }],- },- };+ it("drops the slot on item_aborted: nothing durable is coming", () => {+ const opened = openStreamingSlot(started("item-1"), [mockMessageEvent]);+ const streamed = appendStreamingDeltas(+ [delta("item-1", "half a sentence")],+ opened,+ );- const result = handleEventForUI(planningFinal, [+ expect(abortStreamingSlot("item-1", streamed)).toEqual([mockMessageEvent,- mainDelta,- planningDelta,]);-- expect(result).toEqual([mockMessageEvent, mainDelta, planningFinal]);});- it("main final preserves a still-live planning-agent delta (#1656)", () => {- const mainDelta = makeStreamingDelta("delta-main", "Main says hello");- const planningDelta = {- ...makeStreamingDelta("delta-planning", "Planning still typing"),+ it("clears open slots for one socket only", () => {+ const main = openStreamingSlot(started("main-item"), [mockMessageEvent]);+ const both = openStreamingSlot(started("plan-item"), main, {isFromPlanningAgent: true,- };- const mainFinal = {- ...mockAgentMessageEvent,- id: "main-final",- llm_message: {- role: "assistant" as const,- content: [{ type: "text" as const, text: "Main says hello" }],- },- };+ });- const result = handleEventForUI(mainFinal, [- mockMessageEvent,- mainDelta,- planningDelta,+ expect(clearStreamingSlots(both).map((event) => event.id)).toEqual([+ mockMessageEvent.id,+ "plan-item",+ ]);+ expect(clearStreamingSlots(both, true).map((event) => event.id)).toEqual([+ mockMessageEvent.id,+ "main-item",]);-- expect(result).toEqual([mockMessageEvent, planningDelta, mainFinal]);});});@@ -674,351 +618,4 @@ describe("handleEventForUI", () => {// intermediate ActionEvent whose `thought` is that same text. The chat hoists// the action's thought into its own message, so the leftover streaming delta// must not also render the text or it appears twice.- describe("intermediate action / streamed thought reconciliation (#1534)", () => {- const makeThoughtAction = (id: string, thought: string): ActionEvent => ({- ...mockActionEvent,- id,- tool_call_id: `call_${id}`,- thought: [{ type: "text", text: thought }],- });-- it("clears the streamed content from the delta, keeping its reasoning", () => {- const thought = "Let me gather accurate information.";- const delta: StreamingDeltaEvent = {- ...makeStreamingDelta("delta-1", thought),- reasoning_content: "pondering the request",- };- const action = makeThoughtAction("intermediate-1", thought);-- const result = handleEventForUI(action, [mockMessageEvent, delta]);-- expect(result).toEqual([- mockMessageEvent,- { ...delta, content: null },- action,- ]);- });-- it("drops the delta entirely when it has no reasoning left to render", () => {- const thought = "Let me gather accurate information.";- const delta = makeStreamingDelta("delta-1", thought);- const action = makeThoughtAction("intermediate-1", thought);-- const result = handleEventForUI(action, [mockMessageEvent, delta]);-- expect(result).toEqual([mockMessageEvent, action]);- });-- it("reconciles across multiple streamed segments in order", () => {- const first = makeStreamingDelta("delta-1", "Let me gather ");- const merged = handleEventForUI(- makeStreamingDelta("delta-2", "accurate information."),- handleEventForUI(first, [mockMessageEvent]),- );- const action = makeThoughtAction(- "intermediate-1",- "Let me gather accurate information.",- );-- const result = handleEventForUI(action, merged);-- // The merged content delta is fully streamed and has no reasoning, so it- // is dropped and only the action remains.- expect(result).toEqual([mockMessageEvent, action]);- });-- it("leaves the delta untouched when streamed text does not match the thought", () => {- const delta = makeStreamingDelta(- "delta-1",- "some unrelated streamed text",- );- const action = makeThoughtAction(- "intermediate-1",- "An unrelated thought.",- );-- const result = handleEventForUI(action, [mockMessageEvent, delta]);-- expect(result).toEqual([mockMessageEvent, delta, action]);- });-- // Non-native tool call: the delta is `thought` + raw `<function=...>` XML, a- // superset of the thought, so only the marker signal reconciles it.- it("clears the delta when streamed text is the thought plus an unstripped <function=...> block", () => {- const thought = "Coding and executing";- const delta = makeStreamingDelta(- "delta-1",- `${thought}<function=terminal>\n<parameter=command>echo hi</parameter>\n<parameter=security_risk>LOW</parameter>\n</function>`,- );- const action = makeThoughtAction("intermediate-1", thought);-- const result = handleEventForUI(action, [mockMessageEvent, delta]);-- expect(result).toEqual([mockMessageEvent, action]);- });-- // The planning and main sockets share this store, so the marker signal must- // not let one agent's action strip the other's live delta.- it("leaves a marker-bearing delta from the other agent untouched", () => {- const delta = {- ...makeStreamingDelta(- "delta-1",- `Planning<function=terminal>\n<parameter=command>echo hi</parameter>\n</function>`,- ),- isFromPlanningAgent: true,- };- const action = makeThoughtAction(- "intermediate-1",- "Coding and executing",- );-- const result = handleEventForUI(action, [mockMessageEvent, delta]);-- expect(result).toEqual([mockMessageEvent, delta, action]);- });-- it("does not reconcile a ThinkAction (its thought renders separately)", () => {- const thought = "A reasoning step.";- const delta = makeStreamingDelta("delta-1", thought);- const thinkAction: ActionEvent = {- ...mockActionEvent,- id: "think-1",- tool_name: "think",- tool_call_id: "call_think_1",- thought: [{ type: "text", text: thought }],- action: { kind: "ThinkAction", thought },- };-- const result = handleEventForUI(thinkAction, [mockMessageEvent, delta]);-- expect(result).toEqual([mockMessageEvent, delta, thinkAction]);- });-- it("only reconciles the current turn's delta (after the last user message)", () => {- const thought = "Let me gather accurate information.";- const earlierTurnDelta = makeStreamingDelta("delta-old", thought);- const laterUserMessage: MessageEvent = {- ...mockMessageEvent,- id: "user-2",- };- const action = makeThoughtAction("intermediate-1", thought);-- const result = handleEventForUI(action, [- mockMessageEvent,- earlierTurnDelta,- laterUserMessage,- ]);-- // The delta belongs to a turn before the latest user message, so it is- // left intact and the action is appended normally.- expect(result).toEqual([- mockMessageEvent,- earlierTurnDelta,- laterUserMessage,- action,- ]);- });-- it("reconciles even when the thought is whitespace-trimmed vs the stream", () => {- // The SDK strips assistant text, so the action's thought can lack the- // trailing newline the model streamed before the tool call.- const delta = makeStreamingDelta(- "delta-1",- "Let me gather information.\n",- );- const action = makeThoughtAction(- "intermediate-1",- "Let me gather information.",- );-- const result = handleEventForUI(action, [mockMessageEvent, delta]);-- // Match succeeds despite the trailing newline, so the delta is dropped.- expect(result).toEqual([mockMessageEvent, action]);- });-- it("only folds in the current step's trailing delta, not an earlier step's", () => {- // An earlier step's delta still carrying content sits before this step's- // observation; it must NOT be joined into the match.- const earlierDelta = makeStreamingDelta(- "delta-early",- "Earlier step text.",- );- const currentDelta = makeStreamingDelta(- "delta-current",- "Current step text.",- );- const action = makeThoughtAction("intermediate-2", "Current step text.");-- const result = handleEventForUI(action, [- mockMessageEvent,- earlierDelta,- mockObservationEvent,- currentDelta,- ]);-- // Only the trailing (current) delta is reconciled and dropped; the- // earlier delta is untouched.- expect(result).toEqual([- mockMessageEvent,- earlierDelta,- mockObservationEvent,- action,- ]);- });-- it("drops the delta instead of keeping its reasoning when the action carries reasoning", () => {- const thought = "Let me gather accurate information.";- const delta: StreamingDeltaEvent = {- ...makeStreamingDelta("delta-1", thought),- reasoning_content: "streamed reasoning",- };- const action: ActionEvent = {- ...makeThoughtAction("intermediate-1", thought),- reasoning_content: "finalized reasoning",- };-- const result = handleEventForUI(action, [mockMessageEvent, delta]);-- // The action renders the Thinking section itself, so the delta is fully- // redundant and dropped β no leftover reasoning-only delta.- expect(result).toEqual([mockMessageEvent, action]);- });- });-- describe("intermediate action / streamed reasoning reconciliation", () => {- const REASONING = "Let me read the full PRD to understand all of it.";-- const makeReasoningAction = (thought: string[]): ActionEvent => ({- ...mockActionEvent,- id: "intermediate-1",- tool_call_id: "call_intermediate_1",- thought: thought.map((text) => ({ type: "text", text })),- reasoning_content: REASONING,- });-- it("drops a reasoning-only delta when the action has no thought", () => {- const delta: StreamingDeltaEvent = {- ...makeStreamingDelta("delta-1", null),- reasoning_content: REASONING,- };- const action = makeReasoningAction([]);-- const result = handleEventForUI(action, [mockMessageEvent, delta]);-- expect(result).toEqual([mockMessageEvent, action]);- });-- it("drops a reasoning-only delta when the thought does not match it", () => {- const delta: StreamingDeltaEvent = {- ...makeStreamingDelta("delta-1", null),- reasoning_content: REASONING,- };- const action = makeReasoningAction(["Reading the PRD now."]);-- const result = handleEventForUI(action, [mockMessageEvent, delta]);-- expect(result).toEqual([mockMessageEvent, action]);- });-- it("keeps unmatched streamed text while clearing the duplicated reasoning", () => {- const delta: StreamingDeltaEvent = {- ...makeStreamingDelta("delta-1", "some unrelated streamed text"),- reasoning_content: REASONING,- };- const action = makeReasoningAction(["An unrelated thought."]);-- const result = handleEventForUI(action, [mockMessageEvent, delta]);-- expect(result).toEqual([- mockMessageEvent,- { ...delta, reasoning_content: null },- action,- ]);- });-- it("leaves the delta untouched when the action carries no reasoning", () => {- const delta: StreamingDeltaEvent = {- ...makeStreamingDelta("delta-1", null),- reasoning_content: REASONING,- };- const action: ActionEvent = {- ...mockActionEvent,- id: "intermediate-1",- tool_call_id: "call_intermediate_1",- thought: [],- };-- const result = handleEventForUI(action, [mockMessageEvent, delta]);-- // The delta is the sole reasoning carrier, so it must survive.- expect(result).toEqual([mockMessageEvent, delta, action]);- });-- it("only reconciles the current step's trailing delta run", () => {- const earlierDelta: StreamingDeltaEvent = {- ...makeStreamingDelta("delta-earlier", null),- reasoning_content: "an earlier step's reasoning",- };- const delta: StreamingDeltaEvent = {- ...makeStreamingDelta("delta-1", null),- reasoning_content: REASONING,- };- const action = makeReasoningAction([]);-- const result = handleEventForUI(action, [- mockMessageEvent,- earlierDelta,- mockObservationEvent,- delta,- ]);-- expect(result).toEqual([- mockMessageEvent,- earlierDelta,- mockObservationEvent,- action,- ]);- });-- it("preserves a still-live planning-agent delta (#1656)", () => {- // Main and planning sockets share this event store. A main-agent action- // supersedes only the main agent's streamed reasoning; the planning- // agent's live reasoning must survive.- const planningDelta = {- ...makeStreamingDelta("delta-planning", null),- reasoning_content: "Planning agent is still reasoning",- isFromPlanningAgent: true,- };- const mainDelta: StreamingDeltaEvent = {- ...makeStreamingDelta("delta-main", null),- reasoning_content: REASONING,- };- const action = makeReasoningAction([]);-- const result = handleEventForUI(action, [- mockMessageEvent,- planningDelta,- mainDelta,- ]);-- expect(result).toEqual([mockMessageEvent, planningDelta, action]);- });-- it("leaves the planning agent's reasoning alone when only it streamed (#1656)", () => {- const planningDelta = {- ...makeStreamingDelta("delta-planning", null),- reasoning_content: "Planning agent is still reasoning",- isFromPlanningAgent: true,- };- const action = makeReasoningAction([]);-- const result = handleEventForUI(action, [- mockMessageEvent,- planningDelta,- ]);-- expect(result).toEqual([mockMessageEvent, planningDelta, action]);- });- });});diff --git a/__tests__/utils/session-seq-cursor.test.ts b/__tests__/utils/session-seq-cursor.test.tsnew file mode 100644index 0000000000..a14949625f--- /dev/null+++ b/__tests__/utils/session-seq-cursor.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";+import { createSeqCursor } from "#/utils/session-seq-cursor";++describe("createSeqCursor", () => {+ it("is null until a connection starts it", () => {+ const cursor = createSeqCursor();+ cursor.observe(5);+ expect(cursor.value).toBeNull();+ });++ it("advances through contiguous seqs", () => {+ const cursor = createSeqCursor();+ cursor.start(-1);+ [0, 1, 2].forEach(cursor.observe);+ expect(cursor.value).toBe(2);+ });++ it("holds below a gap and closes it once the missing seq arrives", () => {+ const cursor = createSeqCursor();+ cursor.start(3);+ cursor.observe(5);+ cursor.observe(6);+ expect(cursor.value).toBe(3);++ cursor.observe(4);+ expect(cursor.value).toBe(6);+ });++ it("ignores replays at or below the cursor", () => {+ const cursor = createSeqCursor();+ cursor.start(10);+ cursor.observe(10);+ cursor.observe(2);+ expect(cursor.value).toBe(10);+ });++ it("forgets seqs past a gap on restart, since they are replayed", () => {+ const cursor = createSeqCursor();+ cursor.start(0);+ cursor.observe(2);+ cursor.start(cursor.value ?? -1);+ cursor.observe(1);+ expect(cursor.value).toBe(1);+ });++ it("clears back to no position", () => {+ const cursor = createSeqCursor();+ cursor.start(7);+ cursor.clear();+ expect(cursor.value).toBeNull();+ });+});diff --git a/__tests__/utils/streaming-delta-batcher.test.ts b/__tests__/utils/streaming-delta-batcher.test.tsindex 25f44f2668..ef184e85a5 100644--- a/__tests__/utils/streaming-delta-batcher.test.ts+++ b/__tests__/utils/streaming-delta-batcher.test.ts@@ -4,21 +4,24 @@ import {DeltaFlushScheduler,} from "#/utils/streaming-delta-batcher";import { useEventStore } from "#/stores/use-event-store";-import { StreamingDeltaEvent } from "#/types/agent-server/core/events/streaming-delta-event";+import type { DeltaFrame } from "#/types/agent-server/session-frames";import { MessageEvent } from "#/types/agent-server/core";import { isStreamingDeltaEvent } from "#/types/agent-server/type-guards";+const ITEM_ID = "agent-1";+const makeDelta = (- id: string,- content: string | null,- reasoning: string | null = null,-): StreamingDeltaEvent => ({- id,- timestamp: "2024-03-01T00:00:00Z",- source: "agent",- kind: "StreamingDeltaEvent",+ order: number,+ content: string,+ kind: DeltaFrame["kind"] = "text",+ itemId = ITEM_ID,+): DeltaFrame => ({+ type: "delta",+ item_id: itemId,+ attempt: 1,+ order,+ kind,content,- reasoning_content: reasoning,});/**@@ -52,89 +55,75 @@ function manualScheduler() {describe("createStreamingDeltaBatcher", () => {it("coalesces adjacent deltas into a single commit per frame", () => {- const commits: StreamingDeltaEvent[] = [];+ const commits: DeltaFrame[][] = [];const clock = manualScheduler();const batcher = createStreamingDeltaBatcher(- (delta) => commits.push(delta),+ (frames) => commits.push(frames),clock.scheduler,);- batcher.enqueue(makeDelta("d1", "Hello"));- batcher.enqueue(makeDelta("d2", ", "));- batcher.enqueue(makeDelta("d3", "world"));-- // Nothing commits until the frame fires, and three enqueues schedule only- // ONE frame (not one per delta).+ batcher.enqueue(makeDelta(0, "Hello"));+ batcher.enqueue(makeDelta(1, ", "));+ batcher.enqueue(makeDelta(2, "world"));expect(commits).toHaveLength(0);expect(clock.pendingFrames()).toBe(1);clock.tick();-expect(commits).toHaveLength(1);- expect(commits[0].content).toBe("Hello, world");- // The coalesced event keeps the first delta's identity.- expect(commits[0].id).toBe("d1");+ expect(commits[0].map((frame) => frame.content).join("")).toBe(+ "Hello, world",+ );});- it("merges content and reasoning_content independently, in order", () => {- const commits: StreamingDeltaEvent[] = [];+ it("keeps each frame's kind and order intact for the store to apply", () => {+ const commits: DeltaFrame[][] = [];const clock = manualScheduler();const batcher = createStreamingDeltaBatcher(- (delta) => commits.push(delta),+ (frames) => commits.push(frames),clock.scheduler,);- batcher.enqueue(makeDelta("d1", "ans", "think-"));- batcher.enqueue(makeDelta("d2", "wer", null));- batcher.enqueue(makeDelta("d3", null, "more"));+ batcher.enqueue(makeDelta(0, "think-", "reasoning"));+ batcher.enqueue(makeDelta(1, "ans"));+ batcher.enqueue(makeDelta(2, "more", "reasoning"));clock.tick();- expect(commits).toHaveLength(1);- expect(commits[0].content).toBe("answer");- expect(commits[0].reasoning_content).toBe("think-more");+ expect(commits[0].map((frame) => [frame.kind, frame.content])).toEqual([+ ["reasoning", "think-"],+ ["text", "ans"],+ ["reasoning", "more"],+ ]);});it("flush() commits synchronously and cancels the scheduled frame", () => {- const commits: StreamingDeltaEvent[] = [];+ const commits: DeltaFrame[][] = [];const clock = manualScheduler();const batcher = createStreamingDeltaBatcher(- (delta) => commits.push(delta),+ (frames) => commits.push(frames),clock.scheduler,);- batcher.enqueue(makeDelta("d1", "a"));- batcher.enqueue(makeDelta("d2", "b"));+ batcher.enqueue(makeDelta(0, "a"));+ batcher.enqueue(makeDelta(1, "b"));batcher.flush();expect(commits).toHaveLength(1);- expect(commits[0].content).toBe("ab");- // The pending frame was cancelled, so ticking must not double-commit.expect(clock.pendingFrames()).toBe(0);- clock.tick();- expect(commits).toHaveLength(1);- });-- it("flush() is a no-op when nothing is buffered", () => {- const commits: StreamingDeltaEvent[] = [];- const clock = manualScheduler();- const batcher = createStreamingDeltaBatcher(- (delta) => commits.push(delta),- clock.scheduler,- );+ // Nothing buffered: a second flush is a no-op.batcher.flush();- expect(commits).toHaveLength(0);+ expect(commits).toHaveLength(1);});- it("reset() drops buffered deltas without committing", () => {- const commits: StreamingDeltaEvent[] = [];+ it("reset() drops buffered deltas without committing them", () => {+ const commits: DeltaFrame[][] = [];const clock = manualScheduler();const batcher = createStreamingDeltaBatcher(- (delta) => commits.push(delta),+ (frames) => commits.push(frames),clock.scheduler,);- batcher.enqueue(makeDelta("d1", "lost"));+ batcher.enqueue(makeDelta(0, "lost"));batcher.reset();clock.tick();@@ -143,10 +132,10 @@ describe("createStreamingDeltaBatcher", () => {});it("preserves text byte-for-byte and order across thousands of 1-char deltas faster than 60Hz", () => {- const commits: StreamingDeltaEvent[] = [];+ const commits: DeltaFrame[][] = [];const clock = manualScheduler();const batcher = createStreamingDeltaBatcher(- (delta) => commits.push(delta),+ (frames) => commits.push(frames),clock.scheduler,);@@ -155,20 +144,23 @@ describe("createStreamingDeltaBatcher", () => {for (let i = 0; i < total; i += 1) {const char = String.fromCharCode(97 + (i % 26));expected += char;- batcher.enqueue(makeDelta(`d${i}`, char));+ batcher.enqueue(makeDelta(i, char));// A frame only every 100 deltas => deltas arrive far faster than frames.if (i % 100 === 99) {clock.tick();}}- batcher.flush(); // boundary flush, as a non-delta event would trigger+ batcher.flush(); // boundary flush, as any non-delta frame would trigger// Commits are bounded by frames, not by provider chunk count.expect(commits.length).toBeLessThan(total);expect(commits.length).toBeLessThanOrEqual(total / 100 + 1);- // Concatenating the per-frame batches reproduces the stream exactly (the- // store folds these into one accumulating event by position).- expect(commits.map((delta) => delta.content).join("")).toBe(expected);+ expect(+ commits+ .flat()+ .map((frame) => frame.content)+ .join(""),+ ).toBe(expected);});});@@ -182,33 +174,39 @@ describe("createStreamingDeltaBatcher wired into the event store", () => {extended_content: [],};- it("coalesces deltas across frames, then reconciles into one bubble when the final message arrives", () => {+ it("coalesces deltas across frames, then retires the slot when the durable message arrives", () => {useEventStore.getState().clearEvents();const clock = manualScheduler();// Commit into the real store exactly as ConversationWebSocketProvider does.const batcher = createStreamingDeltaBatcher(- (delta) => useEventStore.getState().addEvent(delta),+ (frames) => useEventStore.getState().appendStreamingDeltas(frames),clock.scheduler,);useEventStore.getState().addEvent(userMessage);+ useEventStore+ .getState()+ .openStreamingSlot({ type: "item_started", item_id: ITEM_ID });// Stream one char per delta, flushing a frame only every 5 chars, so deltas// arrive faster than frames β the case where the UI used to fall behind.const streamed = "I'll start working on that.";[...streamed].forEach((char, i) => {- batcher.enqueue(makeDelta(`d${i}`, char));+ batcher.enqueue(makeDelta(i, char));if (i % 5 === 4) {clock.tick();}});-- // A non-delta event (the final agent message) arrives. The provider flushes- // buffered deltas first, so the durable message can never overtake its own- // streamed text.batcher.flush();++ const slot = useEventStore+ .getState()+ .uiEvents.find((event) => isStreamingDeltaEvent(event));+ expect(slot?.content).toBe(streamed);++ // The durable message carries the slot's id, so it retires it outright.const finalMessage: MessageEvent = {- id: "agent-1",+ id: ITEM_ID,timestamp: "2024-04-01T00:00:00Z",source: "agent",llm_message: {@@ -221,15 +219,13 @@ describe("createStreamingDeltaBatcher wired into the event store", () => {useEventStore.getState().addEvent(finalMessage);const state = useEventStore.getState();- // The user message plus a single reconciled agent bubble β the canonical- // final message supersedes the streamed deltas rather than duplicating them.expect(state.uiEvents).toHaveLength(2);const bubble = state.uiEvents[1] as MessageEvent;- expect(bubble.id).toBe("agent-1");+ expect(bubble.id).toBe(ITEM_ID);expect(bubble.llm_message.content).toEqual([{ type: "text", text: "I'll start working on that. Done." },]);- // No provisional delta survives, so the streamed text renders exactly once.+ // No provisional slot survives, so the streamed text renders exactly once.expect(state.uiEvents.some((event) => isStreamingDeltaEvent(event))).toBe(false,);diff --git a/__tests__/utils/websocket-url.test.ts b/__tests__/utils/websocket-url.test.tsindex 132bdd26c5..5ed5ab6d61 100644--- a/__tests__/utils/websocket-url.test.ts+++ b/__tests__/utils/websocket-url.test.ts@@ -64,7 +64,7 @@ describe("websocket-url utilities", () => {"conv-123","https://example.com/api/conversations/conv-123",);- expect(result).toBe("wss://example.com/sockets/events/conv-123");+ expect(result).toBe("wss://example.com/sockets/session/conv-123");});it("should build WebSocket URL with path prefix for proxy deployment", () => {@@ -73,7 +73,7 @@ describe("websocket-url utilities", () => {"https://openhands.example.com/runtime/55313/api/conversations/abc123",);expect(result).toBe(- "wss://openhands.example.com/runtime/55313/sockets/events/abc123",+ "wss://openhands.example.com/runtime/55313/sockets/session/abc123",);});@@ -87,7 +87,7 @@ describe("websocket-url utilities", () => {"conv-123","http://localhost:3000/api/conversations/conv-123",);- expect(result).toBe("ws://localhost:3000/sockets/events/conv-123");+ expect(result).toBe("ws://localhost:3000/sockets/session/conv-123");});it("should use ws for a remote HTTP page served by the local ingress", () => {@@ -102,13 +102,13 @@ describe("websocket-url utilities", () => {"http://localhost:8000/api/conversations/conv-123",);expect(result).toBe(- "ws://spark-1874.tailae62af.ts.net:8000/sockets/events/conv-123",+ "ws://spark-1874.tailae62af.ts.net:8000/sockets/session/conv-123",);});it("should fallback to window.location.host for null URL", () => {const result = buildWebSocketUrl("conv-123", null);- expect(result).toBe("wss://localhost:3001/sockets/events/conv-123");+ expect(result).toBe("wss://localhost:3001/sockets/session/conv-123");});it("should handle complex path prefixes", () => {@@ -117,7 +117,7 @@ describe("websocket-url utilities", () => {"https://app.example.com/org/team/runtime/12345/api/conversations/test-conv",);expect(result).toBe(- "wss://app.example.com/org/team/runtime/12345/sockets/events/test-conv",+ "wss://app.example.com/org/team/runtime/12345/sockets/session/test-conv",);});});diff --git a/config/defaults.json b/config/defaults.jsonindex 66ac1a7fb7..c83f45692b 100644--- a/config/defaults.json+++ b/config/defaults.json@@ -6,7 +6,7 @@"automation": "1.15.1"},"compatibility": {- "minimumAgentServer": "1.28.0"+ "minimumAgentServer": "1.47.0"},"images": {"agentServer": "ghcr.io/openhands/agent-server",diff --git a/docs/ACP_AGENTS.md b/docs/ACP_AGENTS.mdindex 5c54c16437..b73475733d 100644--- a/docs/ACP_AGENTS.md+++ b/docs/ACP_AGENTS.md@@ -148,11 +148,11 @@ point Canvas at it). In short:# canvas_ui_control calls use client_tools; the Python mount keeps# pre-migration conversations loadable when persisted metadata imports# canvas_ui_tool.-# Minimum image: 1.28.0-python (first compatible ACP provider/model protocol-# surface for current Canvas). Override SHA with a newer build.+# Minimum image: 1.47.0-python (Canvas's minimumAgentServer: the session+# socket). Override SHA with a newer build.docker run -d --name oh-acp -p 8010:8000 -v acp-data:/workspace \-v "$(pwd)/tools:/canvas-tools:ro" -e OH_EXTRA_PYTHON_PATH=/canvas-tools \- ghcr.io/openhands/agent-server:1.28.0-python+ ghcr.io/openhands/agent-server:1.47.0-python# 2. Canvas pointed at the container.VITE_BACKEND_BASE_URL=http://localhost:8010 npm run dev:frontenddiff --git a/src/api/agent-server-compatibility-prerelease.test.ts b/src/api/agent-server-compatibility-prerelease.test.tsindex da08039e5d..d69d7575e5 100644--- a/src/api/agent-server-compatibility-prerelease.test.ts+++ b/src/api/agent-server-compatibility-prerelease.test.ts@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest";vi.mock("../../config/defaults.json", () => ({default: {compatibility: {- minimumAgentServer: "1.28.0-rc.2",+ minimumAgentServer: "1.47.0-rc.2",},},}));@@ -21,27 +21,27 @@ const serverInfo = (version: string): AgentServerInfo =>describe("agent-server prerelease minimum compatibility", () => {it("accepts the stable release for a prerelease minimum", () => {- expect(MINIMUM_COMPATIBLE_AGENT_SERVER_VERSION).toBe("1.28.0-rc.2");+ expect(MINIMUM_COMPATIBLE_AGENT_SERVER_VERSION).toBe("1.47.0-rc.2");expect(() =>- assertAgentServerVersionIsSupported(serverInfo("1.28.0")),+ assertAgentServerVersionIsSupported(serverInfo("1.47.0")),).not.toThrow();- expect(compareAgentServerVersions("1.28.0", "1.28.0-rc.2")).toBe(1);+ expect(compareAgentServerVersions("1.47.0", "1.47.0-rc.2")).toBe(1);});it("normalizes decorated input versions through the public comparator", () => {- expect(compareAgentServerVersions(" v1.28.0+build.7 ", "1.28.0")).toBe(0);+ expect(compareAgentServerVersions(" v1.47.0+build.7 ", "1.47.0")).toBe(0);});it("compares prerelease identifiers at the configured version boundary", () => {expect(() =>- assertAgentServerVersionIsSupported(serverInfo("1.28.0-rc.1")),+ assertAgentServerVersionIsSupported(serverInfo("1.47.0-rc.1")),).toThrow(AgentServerUnsupportedVersionError);expect(() =>- assertAgentServerVersionIsSupported(serverInfo("1.28.0-rc.2")),+ assertAgentServerVersionIsSupported(serverInfo("1.47.0-rc.2")),).not.toThrow();expect(() =>- assertAgentServerVersionIsSupported(serverInfo("1.28.0-rc.3")),+ assertAgentServerVersionIsSupported(serverInfo("1.47.0-rc.3")),).not.toThrow();});});diff --git a/src/api/agent-server-compatibility.test.ts b/src/api/agent-server-compatibility.test.tsindex 8e95df8222..c4e1e5610b 100644--- a/src/api/agent-server-compatibility.test.ts+++ b/src/api/agent-server-compatibility.test.ts@@ -83,7 +83,7 @@ describe("agent-server version compatibility", () => {});});- it.each(["0.99.99", "1.27.999", "1.28.0-rc.1"])(+ it.each(["0.99.99", "1.27.999", "1.47.0-rc.1"])("rejects older version %s",(version) => {const error = getThrownError(() =>@@ -101,10 +101,10 @@ describe("agent-server version compatibility", () => {it.each([MINIMUM_COMPATIBLE_AGENT_SERVER_VERSION,- "1.28.1",- "1.29.0",+ "1.47.1",+ "1.48.0","2.0.0",- " v1.28.0+build.7 ",+ " v1.47.0+build.7 ",])("accepts compatible version %s", (version) => {expect(() =>assertAgentServerVersionIsSupported(serverInfo(version)),@@ -115,9 +115,9 @@ describe("agent-server version compatibility", () => {{ version: undefined, display: null },{ version: "unknown", display: null },{ version: "dev-build", display: null },- { version: "1.28.0", display: "1.28.0" },- { version: " v1.28.0+build.7 ", display: "v1.28.0+build.7" },- { version: "1.28.0-rc.1", display: "1.28.0-rc.1" },+ { version: "1.47.0", display: "1.47.0" },+ { version: " v1.47.0+build.7 ", display: "v1.47.0+build.7" },+ { version: "1.47.0-rc.1", display: "1.47.0-rc.1" },])("displays $version as $display", ({ version, display }) => {expect(getDisplayAgentServerVersion(serverInfo(version))).toBe(display);});diff --git a/src/components/conversation-events/chat/event-message-components/user-assistant-event-message.tsx b/src/components/conversation-events/chat/event-message-components/user-assistant-event-message.tsxindex d3792656e8..a2b89387ee 100644--- a/src/components/conversation-events/chat/event-message-components/user-assistant-event-message.tsx+++ b/src/components/conversation-events/chat/event-message-components/user-assistant-event-message.tsx@@ -7,7 +7,10 @@ import { ImageCarousel } from "../../../features/images/image-carousel";import { parseMessageFromEvent } from "../event-content-helpers/parse-message-from-event";import { CriticResultDisplay } from "./critic-result-display";import { CollapsibleThinking } from "./collapsible-thinking";-import { splitInlineThink } from "../event-thought-helpers";+import {+ getReasoningContent,+ splitInlineThink,+} from "../event-thought-helpers";import RepoForkedIcon from "#/icons/repo-forked.svg?react";import { I18nKey } from "#/i18n/declaration";import { useOptionalConversationId } from "#/hooks/use-conversation-id";@@ -42,10 +45,19 @@ function UserAssistantEventMessageComponent({const parsed = parseMessageFromEvent(event);// Route an inline <think> block (e.g. from a streamed reply) to the thinking// section so reloaded conversations match the live rendering.- const { reasoning, message } =+ const { reasoning: inlineThink, message } =event.source === "agent"? splitInlineThink(parsed): { reasoning: "", message: parsed };+ // The finished message replaces its streaming slot outright, so reasoning the+ // model streamed must render from the message itself or it vanishes on+ // finalize (and never shows after a reload).+ const reasoning = [+ event.source === "agent" ? getReasoningContent(event.llm_message) : "",+ inlineThink,+ ]+ .filter(Boolean)+ .join("\n\n");const imageUrls: string[] = [];if (Array.isArray(event.llm_message.content)) {diff --git a/src/components/conversation-events/chat/event-message.tsx b/src/components/conversation-events/chat/event-message.tsxindex 2fea757370..431f93fa53 100644--- a/src/components/conversation-events/chat/event-message.tsx+++ b/src/components/conversation-events/chat/event-message.tsx@@ -37,6 +37,7 @@ import { HookExecutionEventMessage } from "./event-message-components/hook-execuimport { createSkillReadyEvent } from "./event-content-helpers/create-skill-ready-event";import { shouldShowPlanPreview } from "./hooks/use-plan-preview-events";import { getReasoningContent, splitInlineThink } from "./event-thought-helpers";+import { useStreamedText } from "#/hooks/use-streamed-text";interface EventMessageProps {event: OpenHandsEvent & { isFromPlanningAgent?: boolean };@@ -194,6 +195,13 @@ function EventMessageComponent({// Read isFromPlanningAgent directly from the event objectconst isFromPlanningAgent = event.isFromPlanningAgent || false;+ // Streaming slots render on a clock rather than at the granularity the+ // network delivered (#15493). Unconditional: hooks cannot be nested in the+ // per-kind branches below, and a non-slot event has no streamed content.+ const streamedContent = useStreamedText(+ isStreamingDeltaEvent(event) ? (event.content ?? "") : "",+ );+// Common props for components that need themconst commonProps = {isLastMessage,@@ -234,7 +242,7 @@ function EventMessageComponent({if (isStreamingDeltaEvent(event)) {// Route an inline <think> block to the thinking section, not the bubble.const { reasoning: inlineThink, message } = splitInlineThink(- event.content ?? "",+ streamedContent,{ streaming: true },);const reasoningContent = [event.reasoning_content ?? "", inlineThink]diff --git a/src/components/conversation-events/chat/event-thought-helpers.ts b/src/components/conversation-events/chat/event-thought-helpers.tsindex 101240af65..4f7a43c575 100644--- a/src/components/conversation-events/chat/event-thought-helpers.ts+++ b/src/components/conversation-events/chat/event-thought-helpers.ts@@ -25,7 +25,9 @@ export const getActionThoughtText = (action: ActionEvent): string =>* models). Falls back to the text from `thinking_blocks` (Anthropic* extended thinking). Returns an empty string when neither is available.*/-export const getReasoningContent = (action: ActionEvent): string => {+export const getReasoningContent = (+ action: Partial<Pick<ActionEvent, "reasoning_content" | "thinking_blocks">>,+): string => {if (action.reasoning_content) {return action.reasoning_content;}diff --git a/src/contexts/conversation-websocket-context.tsx b/src/contexts/conversation-websocket-context.tsxindex c5ec28b045..31ec65b489 100644--- a/src/contexts/conversation-websocket-context.tsx+++ b/src/contexts/conversation-websocket-context.tsx@@ -39,9 +39,12 @@ import {isSwitchLLMObservationEvent,isClassifyAndSwitchLLMObservationEvent,isCanvasUIActionEvent,- isStreamingDeltaEvent,isLaunchChildConversationActionEvent,} from "#/types/agent-server/type-guards";+import {+ asSessionFrame,+ type SessionFrame,+} from "#/types/agent-server/session-frames";import {createStreamingDeltaBatcher,StreamingDeltaBatcher,@@ -55,6 +58,7 @@ import type {} from "#/types/agent-server/core/events/conversation-state-event";import { handleActionEventCacheInvalidation } from "#/utils/cache-utils";import { buildWebSocketUrl } from "#/utils/websocket-url";+import { createSeqCursor, type SeqCursor } from "#/utils/session-seq-cursor";import type {AppConversation,SendMessageRequest,@@ -122,6 +126,62 @@ function extractMessageEventText(.join("");}+/**+ * Route one frame of `/sockets/session/{id}`.+ *+ * Progress frames (`item_started` / `delta` / `item_aborted`) are applied to+ * the streaming slot here and produce no event. Durable and transient frames+ * are unwrapped and returned for the caller's normal event handling; a durable+ * frame also advances the resume cursor and stamps its `seq` on the event, so+ * the UI can place a slot relative to it.+ */+const routeSessionFrame = (+ raw: unknown,+ batcher: StreamingDeltaBatcher | null,+ /** Report a durable frame's `seq` to this socket's resume cursor. */+ advanceCursor: (seq: number) => void,+ slotMeta: { isFromPlanningAgent?: boolean } = {},+): unknown | null => {+ const frame: SessionFrame | null = asSessionFrame(raw);+ if (!frame) {+ return null;+ }++ if (frame.type === "delta") {+ batcher?.enqueue(frame);+ return null;+ }++ // Nothing else may overtake text that was streamed ahead of it.+ batcher?.flush();++ switch (frame.type) {+ case "item_started":+ useEventStore.getState().openStreamingSlot(frame, slotMeta);+ return null;+ case "item_aborted":+ // Nothing durable is coming to supersede the provisional text.+ useEventStore.getState().abortStreamingSlot(frame.item_id, frame.attempt);+ return null;+ case "durable":+ advanceCursor(frame.seq);+ return { ...frame.event, seq: frame.seq };+ case "transient":+ return frame.event;+ case "error":+ // The server answers a rejected inbound message with an ErrorFrame and+ // keeps the socket open ("not worth dropping over"), so there is no+ // reconnect and nothing else will ever surface this to the user.+ useErrorMessageStore+ .getState()+ .setErrorMessage(frame.detail, "conversation", frame.code);+ return null;+ default:+ // `sync` needs nothing: the cursor advances on durable frames.+ return null;+ }+};+export function ConversationWebSocketProvider({children,conversationId,@@ -167,22 +227,27 @@ export function ConversationWebSocketProvider({// Separate batchers keep the main and planning streams from ever merging.const mainDeltaBatcherRef = useRef<StreamingDeltaBatcher | null>(null);if (mainDeltaBatcherRef.current === null) {- mainDeltaBatcherRef.current = createStreamingDeltaBatcher((delta) => {- useEventStore.getState().addEvent(delta);+ mainDeltaBatcherRef.current = createStreamingDeltaBatcher((frames) => {+ useEventStore.getState().appendStreamingDeltas(frames);// A delta means connectivity recovered β mirror handleNonErrorEvent.useErrorMessageStore.getState().clearConnectionError();});}const planningDeltaBatcherRef = useRef<StreamingDeltaBatcher | null>(null);if (planningDeltaBatcherRef.current === null) {- planningDeltaBatcherRef.current = createStreamingDeltaBatcher((delta) => {+ planningDeltaBatcherRef.current = createStreamingDeltaBatcher((frames) => {useEventStore.getState()- .addEvent({ ...delta, isFromPlanningAgent: true });+ .appendStreamingDeltas(frames, { isFromPlanningAgent: true });useErrorMessageStore.getState().clearConnectionError();});}+ // Resume cursors, one per socket. Started at connect time (see the lazy+ // `queryParams` below) and advanced per durable frame without re-rendering.+ const mainCursorRef = useRef<SeqCursor>(createSeqCursor());+ const planningCursorRef = useRef<SeqCursor>(createSeqCursor());+// History loading state.// - Main conversation history is now loaded via REST (`useConversationHistory`),// so its loading state mirrors the REST query state (see below).@@ -294,6 +359,20 @@ export function ConversationWebSocketProvider({// refetch never drops a live socket.const isLoadingHistoryMain = !!conversationId && isPreloadingHistory;+ // First-connect cursor from the REST page (see `afterSeq`). Read lazily by+ // the socket's `queryParams`; after the first connect the socket's own+ // cursor takes over.+ const historyAfterSeqRef = useRef<number | null>(null);+ useEffect(() => {+ historyAfterSeqRef.current = preloadedHistory?.afterSeq ?? null;+ }, [preloadedHistory]);++ // The planner has its own log: reset its cursor when it is a different one.+ const planningSocketConversationId = subConversations?.[0]?.id ?? null;+ useEffect(() => {+ planningCursorRef.current.clear();+ }, [planningSocketConversationId]);+// Clear the (global, not conversation-scoped) event store when the active// conversation changes, BEFORE the preloaded-history effect below re-seeds// it. This MUST live here rather than in the route component: a parent's@@ -361,22 +440,6 @@ export function ConversationWebSocketProvider({consumeMatchingPendingMessage,]);- /**- * 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 first REST page lands- * (the WS connection is gated on that β see `wsUrl` below). During- * background refetches `preloadedHistory` keeps the last-known page, so the- * anchor holds steady instead of flipping to null; reconnects read the- * freshest value from the options ref at connect time.- */- const initialAfterTimestamp = useMemo<string | null>(() => {- const events = preloadedHistory?.events ?? [];- const latest = events[events.length - 1];- if (!latest || !("timestamp" in latest) || !latest.timestamp) return null;- return latest.timestamp;- }, [preloadedHistory]);-// Build WebSocket URL from props.//// We deliberately wait for the FIRST history load (`isPending`: no data for@@ -528,6 +591,9 @@ export function ConversationWebSocketProvider({useEffect(() => {hasConnectedRefMain.current = false;hasConnectedRefPlanning.current = false;+ // A cursor is a position in one conversation's log; carrying it into the+ // next would skip that conversation's events below it.+ mainCursorRef.current.clear();// Reset the tracked event ref when conversation changeslatestPlanningFileEventRef.current = null;}, [conversationId]);@@ -553,21 +619,17 @@ export function ConversationWebSocketProvider({const handleMainMessage = useCallback((messageEvent: MessageEvent) => {try {- const event = JSON.parse(messageEvent.data);+ const event = routeSessionFrame(+ JSON.parse(messageEvent.data),+ mainDeltaBatcherRef.current,+ mainCursorRef.current.observe,+ );// History loading for the main conversation is REST-driven now;- // every WS message is a new event we add to the store.+ // every durable frame is a new event we add to the store.// Use type guard to validate v1 event structureif (isAgentServerEvent(event)) {- // Buffer deltas; nothing else in this handler applies to them.- if (isStreamingDeltaEvent(event)) {- mainDeltaBatcherRef.current?.enqueue(event);- return;- }- // Flush buffered deltas before this event so it can't overtake them.- mainDeltaBatcherRef.current?.flush();-// A reconnect replays the backlog from a stale anchor. The store// dedups by id, but the side-effects below aren't idempotent, so skip// them for replayed events (#1656).@@ -812,10 +874,18 @@ export function ConversationWebSocketProvider({const handlePlanningMessage = useCallback((messageEvent: MessageEvent) => {try {- const event = JSON.parse(messageEvent.data);+ const event = routeSessionFrame(+ JSON.parse(messageEvent.data),+ planningDeltaBatcherRef.current,+ planningCursorRef.current.observe,+ { isFromPlanningAgent: true },+ );+ if (event === null) {+ return;+ }- // 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+ // Track received events for history loading. Only events count:+ // progress frames are not part of the replayed log.if (isLoadingHistoryPlanning) {receivedEventCountRefPlanning.current += 1;@@ -829,14 +899,6 @@ export function ConversationWebSocketProvider({// Use type guard to validate v1 event structureif (isAgentServerEvent(event)) {- // Buffer deltas (the commit re-applies the planning flag).- if (isStreamingDeltaEvent(event)) {- planningDeltaBatcherRef.current?.enqueue(event);- return;- }- // Flush buffered deltas before this event so it can't overtake them.- planningDeltaBatcherRef.current?.flush();-// Skip non-idempotent side-effects for replayed events, as in the// main handler (#1656).const isDuplicateEvent = useEventStore@@ -1030,15 +1092,17 @@ export function ConversationWebSocketProvider({// Separate WebSocket options for main connectionconst mainWebsocketOptions: WebSocketHookOptions = useMemo(() => {- // 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" };+ // `after_seq` replaces the legacy resend_mode/after_timestamp pair, which+ // compared naive local timestamps. Resolved lazily so a reconnect resumes+ // from the newest `seq` this socket actually saw rather than from a value+ // captured at render. The first connect has no cursor and asks for the+ // whole log (`-1`); the REST preload (`useConversationHistory`) still+ // renders instantly and the event store dedupes the overlap by id.+ const queryParams = () => {+ const cursor = mainCursorRef.current;+ cursor.start(cursor.value ?? historyAfterSeqRef.current ?? -1);+ return { after_seq: String(cursor.value) };+ };return {queryParams,@@ -1048,9 +1112,16 @@ export function ConversationWebSocketProvider({setMainConnectionState("OPEN");hasConnectedRefMain.current = true; // Mark that we've successfully connectedclearConnectionError(); // Clear a previous connection error; keep sticky conversation errors+ // Progress frames are never replayed, so any slot left open across the+ // gap can never be retired. Discard and wait: the durable message is+ // coming on the cursor regardless.+ mainDeltaBatcherRef.current?.reset();+ useEventStore.getState().clearStreamingSlots();},onClose: () => {setMainConnectionState("CLOSED");+ mainDeltaBatcherRef.current?.reset();+ useEventStore.getState().clearStreamingSlots();},onError: () => {setMainConnectionState("CLOSED");@@ -1061,18 +1132,16 @@ export function ConversationWebSocketProvider({},onMessage: handleMainMessage,};- }, [- handleMainMessage,- setErrorMessage,- clearConnectionError,- sessionApiKey,- initialAfterTimestamp,- ]);+ }, [handleMainMessage, setErrorMessage, clearConnectionError, sessionApiKey]);// Separate WebSocket options for planning agent connectionconst planningWebsocketOptions: WebSocketHookOptions = useMemo(() => {- const queryParams: Record<string, string | boolean> = {- resend_all: true,+ // The planner's history is not preloaded over REST, so it always replays+ // from the start on a first connect and from its cursor after that.+ const queryParams = () => {+ const cursor = planningCursorRef.current;+ cursor.start(cursor.value ?? -1);+ return { after_seq: String(cursor.value) };};const planningAgentConversation = subConversations?.[0];@@ -1087,6 +1156,9 @@ export function ConversationWebSocketProvider({setPlanningConnectionState("OPEN");hasConnectedRefPlanning.current = true; // Mark that we've successfully connectedclearConnectionError(); // Clear a previous connection error; keep sticky conversation errors+ // See the main socket: an open slot cannot survive the gap.+ planningDeltaBatcherRef.current?.reset();+ useEventStore.getState().clearStreamingSlots(true);// Fetch expected event count for history loading detectionif (@@ -1113,6 +1185,8 @@ export function ConversationWebSocketProvider({},onClose: () => {setPlanningConnectionState("CLOSED");+ planningDeltaBatcherRef.current?.reset();+ useEventStore.getState().clearStreamingSlots(true);},onError: () => {setPlanningConnectionState("CLOSED");diff --git a/src/hooks/query/use-conversation-history.ts b/src/hooks/query/use-conversation-history.tsindex 2c8c9f44f5..f308c39f60 100644--- a/src/hooks/query/use-conversation-history.ts+++ b/src/hooks/query/use-conversation-history.ts@@ -16,6 +16,13 @@ export interface ConversationHistoryPage {hasMore: boolean;/** Optional `next_page_id` from the server for keyset pagination. */nextPageId: string | null;+ /**+ * 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+ * could not be read.+ */+ afterSeq: number | null;}/**@@ -24,8 +31,8 @@ export interface ConversationHistoryPage {* 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.+ * scrolls up. The session socket then resumes from `afterSeq`, so it neither+ * re-receives the history we already have nor misses what landed meanwhile.*/export const useConversationHistory = (conversationId?: string) => {const { data: conversation } = useUserConversation(conversationId ?? null);@@ -42,7 +49,25 @@ export const useConversationHistory = (conversationId?: string) => {enabled: !!conversationId && !!conversation,queryFn: async () => {if (!conversationId) {- return { events: [], hasMore: false, nextPageId: null };+ return { events: [], hasMore: false, nextPageId: null, afterSeq: null };+ }++ // Read the count first: an unfiltered count is the log length, so every+ // event appended after it has `seq >= count` and is replayed (and+ // deduped against this page) rather than lost.+ const conversationUrl = conversation?.conversation_url ?? null;+ let count: number | null = null;+ if (conversationUrl) {+ try {+ count = await EventService.getEventCount(+ conversationId,+ conversationUrl,+ conversation?.session_api_key ?? null,+ );+ } catch {+ // Not fatal: without a cursor the socket replays the whole log.+ count = null;+ }}const page = await EventService.searchEvents(@@ -68,6 +93,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,};},// Keep the cached page so returning to a conversation renders the@@ -86,8 +112,8 @@ export const useConversationHistory = (conversationId?: string) => {// WebSocket `since` replay on reconnect anyway. retry is capped at 1 so a// slow or failing initial load (60s HTTP timeout per attempt) can't hold// the initial WebSocket gate (see conversation-websocket-context.tsx)- // closed for minutes β on failure the socket connects with- // `resend_mode='all'` instead.+ // closed for minutes β on failure the socket replays the whole log+ // (`after_seq=-1`) instead.staleTime: 0,gcTime: 30 * 60 * 1000, // 30 minutes β keep cached data to render instantly on returnrefetchOnMount: "always",diff --git a/src/hooks/use-streamed-text.ts b/src/hooks/use-streamed-text.tsnew file mode 100644index 0000000000..fd87478dea--- /dev/null+++ b/src/hooks/use-streamed-text.ts@@ -0,0 +1,73 @@+import React from "react";++/**+ * Window over which the unrevealed backlog is drained. Short enough that the+ * text never visibly trails the model, long enough that a burst of tokens+ * reads as typing rather than as a paste.+ */+const DRAIN_WINDOW_MS = 120;++/**+ * Reveal `target` on a clock rather than at the granularity the network+ * happened to deliver it (#15493).+ *+ * The rate is proportional to the backlog, so a fast model is revealed fast+ * and a slow one still reads smoothly; text that is not an extension of what+ * is already on screen (a superseding retry, or a different slot) snaps+ * immediately rather than being re-typed.+ */+export function useStreamedText(target: string): string {+ const [revealed, setRevealed] = React.useState(target);+ const revealedRef = React.useRef(target);+ const frameRef = React.useRef<number | null>(null);++ React.useEffect(() => {+ const commit = (next: string) => {+ revealedRef.current = next;+ setRevealed(next);+ };++ if (+ !target.startsWith(revealedRef.current) ||+ typeof requestAnimationFrame !== "function"+ ) {+ commit(target);+ return undefined;+ }+ if (revealedRef.current.length === target.length) {+ return undefined;+ }++ let lastTick = 0;+ const tick = (now: number) => {+ frameRef.current = null;+ const elapsed = lastTick ? now - lastTick : 16;+ lastTick = now;++ const backlog = target.length - revealedRef.current.length;+ const step = Math.max(+ 1,+ Math.ceil((backlog * elapsed) / DRAIN_WINDOW_MS),+ );+ const nextLength = Math.min(+ target.length,+ revealedRef.current.length + step,+ );+ commit(target.slice(0, nextLength));++ if (nextLength < target.length) {+ frameRef.current = requestAnimationFrame(tick);+ }+ };++ frameRef.current = requestAnimationFrame(tick);+ return () => {+ if (frameRef.current !== null) {+ cancelAnimationFrame(frameRef.current);+ frameRef.current = null;+ }+ };+ }, [target]);++ return revealed;+}diff --git a/src/hooks/use-websocket.ts b/src/hooks/use-websocket.tsindex b483108a2e..8965ffc62c 100644--- a/src/hooks/use-websocket.ts+++ b/src/hooks/use-websocket.ts@@ -3,7 +3,14 @@ import { sendWebSocketAuth } from "#/utils/websocket-auth";import { startHandshakeWatchdog } from "#/utils/websocket-handshake";export interface WebSocketHookOptions {- queryParams?: Record<string, string | boolean>;+ /**+ * Query params for the socket URL. Pass a function when a value must be+ * read at connect time rather than at render time β a resume cursor that+ * advances on every frame would otherwise re-render the owner per event.+ */+ queryParams?:+ | Record<string, string | boolean>+ | (() => Record<string, string | boolean>);sessionApiKey?: string | null;onOpen?: (event: Event) => void;onClose?: (event: CloseEvent) => void;@@ -39,10 +46,11 @@ export const useWebSocket = (url: string, options?: WebSocketHookOptions) => {const connectWebSocket = React.useCallback(() => {// Build URL with query parameters if providedlet wsUrl = url;- if (optionsRef.current?.queryParams) {- const stringParams = Object.entries(- optionsRef.current.queryParams,- ).reduce(+ const { queryParams } = optionsRef.current ?? {};+ if (queryParams) {+ const resolved =+ typeof queryParams === "function" ? queryParams() : queryParams;+ const stringParams = Object.entries(resolved).reduce((acc, [key, value]) => {acc[key] = String(value);return acc;diff --git a/src/mocks/settings-handlers.ts b/src/mocks/settings-handlers.tsindex dd949b1632..607a09df78 100644--- a/src/mocks/settings-handlers.ts+++ b/src/mocks/settings-handlers.ts@@ -675,7 +675,7 @@ const MOCK_VERIFIED_MODELS_BY_PROVIDER = MOCK_MODELS.reduce<// advertised fields (`enable_switch_llm_tool`) that the mocked server's own// profile model would have rejected, and version-gated UI hid controls the// rest of the mocks were serving.-const MOCK_AGENT_SERVER_VERSION = "1.36.1";+const MOCK_AGENT_SERVER_VERSION = "1.48.0";// --- Handlers for options/config/settings ---// Uses wildcard "*" prefix to match both relative paths and absolute URLsdiff --git a/src/stores/use-event-store.ts b/src/stores/use-event-store.tsindex cbfa0f800b..ba9ce88c3b 100644--- a/src/stores/use-event-store.ts+++ b/src/stores/use-event-store.ts@@ -1,15 +1,19 @@import { create } from "zustand";-import { OpenHandsEvent } from "#/types/agent-server/core";import {+ abortStreamingSlot,+ appendStreamingDeltas,+ clearStreamingSlots,handleEventForUI,- isSameStreamingSender,- mergeStreamingDeltaEvent,+ openStreamingSlot,+ type StreamingSlotMeta,+ type UIEvent,} from "#/utils/handle-event-for-ui";-import { isStreamingDeltaEvent } from "#/types/agent-server/type-guards";+import type {+ DeltaFrame,+ ItemStartedFrame,+} from "#/types/agent-server/session-frames";-export type OHEvent = OpenHandsEvent & {- isFromPlanningAgent?: boolean;-};+export type OHEvent = UIEvent;const getEventId = (event: OHEvent): string | number | undefined =>"id" in event ? event.id : undefined;@@ -87,42 +91,41 @@ export interface EventState {* right order.*/clearEventsForConversation: (conversationId: string | null) => void;+ /**+ * Streaming slots. They live only in `uiEvents`: nothing reads `events` for+ * provisional text, and keeping them out means their id β which is the id+ * the durable event will carry β can never be mistaken for one already seen+ * and dedupe the real message away.+ */+ openStreamingSlot: (+ frame: ItemStartedFrame,+ meta?: StreamingSlotMeta,+ ) => void;+ appendStreamingDeltas: (+ frames: DeltaFrame[],+ meta?: StreamingSlotMeta,+ ) => void;+ abortStreamingSlot: (itemId: string, attempt?: number) => void;+ /** Discard every open slot for one socket (on connect and disconnect). */+ clearStreamingSlots: (isFromPlanningAgent?: boolean) => void;}const appendEvent = (state: EventState, event: OHEvent): EventState => {const eventId = getEventId(event);- // Transient deltas merge by position and are never persisted/resent, so skip- // id tracking for them β copying the growing `eventIds` Set per token would- // otherwise be O(n^2).- const isDelta = isStreamingDeltaEvent(event);// Deduplicate: skip if event with same id already exists (O(1) lookup)- if (!isDelta && eventId !== undefined && state.eventIds.has(eventId)) {+ if (eventId !== undefined && state.eventIds.has(eventId)) {return state;}const newEventIds =- !isDelta && eventId !== undefined+ eventId !== undefined? new Set(state.eventIds).add(eventId): state.eventIds;- const lastEventIndex = state.events.length - 1;- const lastEvent = state.events[lastEventIndex];- const shouldMergeStreamingDelta =- lastEvent &&- isDelta &&- isStreamingDeltaEvent(lastEvent) &&- isSameStreamingSender(event, lastEvent);- const events = [...state.events];- if (shouldMergeStreamingDelta) {- events[lastEventIndex] = mergeStreamingDeltaEvent(event, lastEvent);- } else {- events.push(event);- }-return {...state,- events,+ events: [...state.events, event],eventIds: newEventIds,uiEvents: handleEventForUI(event, state.uiEvents),};@@ -167,30 +170,14 @@ export const useEventStore = create<EventState>()((set) => ({for (const event of incoming) {const eventId = getEventId(event);- // See `appendEvent`: transient deltas are not tracked in `eventIds`.- const isDelta = isStreamingDeltaEvent(event);- const isDuplicate =- !isDelta && eventId !== undefined && eventIds.has(eventId);+ const isDuplicate = eventId !== undefined && eventIds.has(eventId);if (!isDuplicate) {added = true;- if (!isDelta && eventId !== undefined) {+ if (eventId !== undefined) {eventIds.add(eventId);}-- const lastEventIndex = events.length - 1;- const lastEvent = events[lastEventIndex];- if (- lastEvent &&- isStreamingDeltaEvent(event) &&- isStreamingDeltaEvent(lastEvent) &&- isSameStreamingSender(event, lastEvent)- ) {- events[lastEventIndex] = mergeStreamingDeltaEvent(event, lastEvent);- } else {- events.push(event);- }-+ events.push(event);uiEvents = handleEventForUI(event, uiEvents);}}@@ -220,6 +207,38 @@ export const useEventStore = create<EventState>()((set) => ({uiEvents: [],loadedConversationId: conversationId,})),+ openStreamingSlot: (frame: ItemStartedFrame, meta: StreamingSlotMeta = {}) =>+ set((state) => {+ // Symmetric with `appendStreamingDeltas`: the durable event being in+ // the store means the stream is over, and a slot opened now could never+ // be retired β `appendEvent` dedupes the durable frame before+ // `handleEventForUI` could replace it.+ if (state.eventIds.has(frame.item_id)) {+ return state;+ }+ const uiEvents = openStreamingSlot(frame, state.uiEvents, meta);+ return uiEvents === state.uiEvents ? state : { ...state, uiEvents };+ }),+ appendStreamingDeltas: (frames: DeltaFrame[], meta: StreamingSlotMeta = {}) =>+ set((state) => {+ const uiEvents = appendStreamingDeltas(frames, state.uiEvents, {+ ...meta,+ // The durable event carries the item's id, so seeing it means the+ // stream is over and a straggling delta must not reopen it.+ isFinished: (itemId) => state.eventIds.has(itemId),+ });+ return uiEvents === state.uiEvents ? state : { ...state, uiEvents };+ }),+ abortStreamingSlot: (itemId: string, attempt?: number) =>+ set((state) => {+ const uiEvents = abortStreamingSlot(itemId, state.uiEvents, attempt);+ return uiEvents === state.uiEvents ? state : { ...state, uiEvents };+ }),+ clearStreamingSlots: (isFromPlanningAgent = false) =>+ set((state) => {+ const uiEvents = clearStreamingSlots(state.uiEvents, isFromPlanningAgent);+ return uiEvents === state.uiEvents ? state : { ...state, uiEvents };+ }),}));// In dev builds, expose the store on `window` so that fixture/previewdiff --git a/src/types/agent-server/core/events/streaming-delta-event.ts b/src/types/agent-server/core/events/streaming-delta-event.tsindex f5c4221da1..f5189efd3d 100644--- a/src/types/agent-server/core/events/streaming-delta-event.ts+++ b/src/types/agent-server/core/events/streaming-delta-event.ts@@ -1,8 +1,17 @@import { BaseEvent } from "../base/event";+/**+ * One open streaming slot, rendered in place of the message that will replace+ * it. Client-minted, never persisted, and not an agent-server event: `id` is+ * the `item_id` of the `item_started` frame that opened it, which is also the+ * id the durable event is built with β so the slot is retired by a single+ * equality test rather than by comparing its text to the message.+ */export interface StreamingDeltaEvent extends BaseEvent {kind: "StreamingDeltaEvent";source: "agent";content: string | null;reasoning_content: string | null;+ /** Attempt currently rendered; a higher one supersedes this text. */+ attempt?: number;}diff --git a/src/types/agent-server/session-frames.ts b/src/types/agent-server/session-frames.tsnew file mode 100644index 0000000000..64ed17fa1d--- /dev/null+++ b/src/types/agent-server/session-frames.ts@@ -0,0 +1,107 @@+import { OpenHandsEvent } from "./core";++/**+ * Frames of `/sockets/session/{conversation_id}` (agent-server+ * `session_protocol.py`). The envelope is deliberately not an `Event`: the+ * durable record rides inside it untouched, and protocol fields live on the+ * envelope. The URL is the protocol version β there is no handshake.+ * Local mirror of software-agent-sdk #4807/#4822; replace with the+ * `@openhands/typescript-client` types once published (software-agent-sdk#4763).+ *+ * Unknown frame types must be ignored: the envelope is allowed to grow.+ */++/** Sent once, before any replay, describing the range about to be sent. */+export interface SyncFrame {+ type: "sync";+ from_seq?: number | null;+ through_seq?: number | null;+}++/** One persisted event, after it is safely on disk. `seq` is its log index. */+export interface DurableFrame {+ type: "durable";+ seq: number;+ event: OpenHandsEvent;+}++/** An event that is published but never persisted, so it carries no `seq`. */+export interface TransientFrame {+ type: "transient";+ event: OpenHandsEvent;+}++/**+ * A stream is opening. `item_id` is the id the durable event will be built+ * with, so the slot it opens is retired by `event.id === item_id`.+ */+export interface ItemStartedFrame {+ type: "item_started";+ item_id: string;+ attempt?: number;+ anchor_seq?: number | null;+}++/** One masked increment of a stream. `order` is monotonic per (item, attempt). */+export interface DeltaFrame {+ type: "delta";+ item_id: string;+ attempt?: number;+ order: number;+ kind?: "text" | "reasoning";+ content: string;+ chunk_id?: string | null;+ choice_index?: number | null;+}++/** A stream ended without producing a durable event. */+export interface ItemAbortedFrame {+ type: "item_aborted";+ item_id: string;+ attempt?: number;+ reason: string;+}++/** A problem with this socket. Distinct from a durable conversation error. */+export interface SessionErrorFrame {+ type: "error";+ code: string;+ detail: string;+}++export type SessionFrame =+ | SyncFrame+ | DurableFrame+ | TransientFrame+ | ItemStartedFrame+ | DeltaFrame+ | ItemAbortedFrame+ | SessionErrorFrame;++const FRAME_TYPES = new Set<SessionFrame["type"]>([+ "sync",+ "durable",+ "transient",+ "item_started",+ "delta",+ "item_aborted",+ "error",+]);++/**+ * Narrow a decoded socket message to a known frame, or `null` for anything+ * this client does not recognize.+ */+export const asSessionFrame = (value: unknown): SessionFrame | null => {+ if (typeof value !== "object" || value === null) {+ return null;+ }+ const { type } = value as { type?: unknown };+ if (+ typeof type !== "string" ||+ !FRAME_TYPES.has(type as SessionFrame["type"])+ ) {+ return null;+ }+ return value as SessionFrame;+};diff --git a/src/utils/handle-event-for-ui.ts b/src/utils/handle-event-for-ui.tsindex 250db11635..444a482496 100644--- a/src/utils/handle-event-for-ui.ts+++ b/src/utils/handle-event-for-ui.ts@@ -1,336 +1,261 @@-import {- ActionEvent,- ImageContent,- OpenHandsEvent,- TextContent,-} from "#/types/agent-server/core";+import { OpenHandsEvent } from "#/types/agent-server/core";import {isACPToolCallEvent,- isActionEvent,- isMessageEvent,isObservationEvent,isStreamingDeltaEvent,} from "#/types/agent-server/type-guards";import { StreamingDeltaEvent } from "#/types/agent-server/core/events/streaming-delta-event";-import {- getReasoningContent,- splitInlineThink,-} from "#/components/conversation-events/chat/event-thought-helpers";--export const mergeStreamingDeltaEvent = (- incoming: StreamingDeltaEvent,- existing: StreamingDeltaEvent,-): StreamingDeltaEvent => ({- ...existing,- content: `${existing.content ?? ""}${incoming.content ?? ""}` || null,- reasoning_content:- `${existing.reasoning_content ?? ""}${incoming.reasoning_content ?? ""}` ||- null,-});+import type {+ DeltaFrame,+ ItemStartedFrame,+} from "#/types/agent-server/session-frames";-// Deltas only merge into one bubble when they share a sender; the planning flag-// is the only discriminator (every delta has `source: "agent"`). Prevents a-// planning-agent delta concatenating onto a main-agent one, misattributed (#1656).-export const isSameStreamingSender = (- a: OpenHandsEvent & { isFromPlanningAgent?: boolean },- b: OpenHandsEvent & { isFromPlanningAgent?: boolean },-): boolean => Boolean(a.isFromPlanningAgent) === Boolean(b.isFromPlanningAgent);--const findLastUserMessageIndex = (events: OpenHandsEvent[]): number => {- for (let index = events.length - 1; index >= 0; index -= 1) {- const event = events[index];- if (isMessageEvent(event) && event.source === "user") {- return index;- }- }- return -1;+/**+ * An event as held by the UI list. `seq` is the log index a `durable` frame+ * carried; slots and transient events have none, which is what makes "has a+ * seq" mean "is resumable".+ */+export type UIEvent = OpenHandsEvent & {+ isFromPlanningAgent?: boolean;+ seq?: number;};-// Join text blocks WITHOUT a separator: streaming deltas concatenate content-// tokens directly with no separator between LLM content blocks, so using "\n"-// here would cause startsWith/findTextSegmentsInOrder to miss when reconciling-// a multi-block message/thought against the already-rendered streaming delta.-const joinTextBlocks = (blocks: (TextContent | ImageContent)[]): string =>- blocks- .filter((block) => block.type === "text")- .map((block) => block.text)- .join("");+export interface StreamingSlotMeta {+ isFromPlanningAgent?: boolean;+}-const findTextSegmentsInOrder = (- text: string,- segments: string[],-): { matched: boolean; lastMatchEnd: number } => {- let searchStart = 0;- let lastMatchEnd = 0;+const attemptOf = (slot: StreamingDeltaEvent): number => slot.attempt ?? 1;- for (const segment of segments) {- const index = text.indexOf(segment, searchStart);- if (index === -1) {- return { matched: false, lastMatchEnd };- }- lastMatchEnd = index + segment.length;- searchStart = lastMatchEnd;- }+/** Slots and events belong to one socket; `seq` only means anything within it. */+const isSameSocket = (event: UIEvent, isFromPlanningAgent: boolean): boolean =>+ Boolean(event.isFromPlanningAgent) === isFromPlanningAgent;- return { matched: true, lastMatchEnd };-};--// Content-bearing streaming deltas of the current turn (after the last user-// message) that share the final event's sender. Reasoning-only deltas are-// excluded: reasoning renders in its own collapsed bubble and never overlaps-// the message text being reconciled. Sender scoping matters because the main-// and planning sockets share this event store β without it, one agent's final-// event would strip the other agent's still-live streamed deltas (#1656).-const getCurrentTurnContentDeltas = (- uiEvents: OpenHandsEvent[],- finalEvent: OpenHandsEvent,-): { event: StreamingDeltaEvent; index: number }[] => {- const lastUserMessageIndex = findLastUserMessageIndex(uiEvents);- return uiEvents- .map((event, index) => ({ event, index }))- .filter(- (item): item is { event: StreamingDeltaEvent; index: number } =>- item.index > lastUserMessageIndex &&- isStreamingDeltaEvent(item.event) &&- (item.event.content?.length ?? 0) > 0 &&- isSameStreamingSender(finalEvent, item.event),- );-};--// The current step's streaming delta(s): the trailing run at the end of-// `uiEvents`. Earlier steps' deltas are separated by their observations, so-// this never folds an earlier step's delta into the current one.-const getTrailingDeltas = (- uiEvents: OpenHandsEvent[],- selects: (event: StreamingDeltaEvent) => boolean,-): { event: StreamingDeltaEvent; index: number }[] => {- const deltas: { event: StreamingDeltaEvent; index: number }[] = [];- for (let index = uiEvents.length - 1; index >= 0; index -= 1) {- const event = uiEvents[index];- if (!isStreamingDeltaEvent(event)) {- break;- }- if (selects(event)) {- deltas.unshift({ event, index });- }- }- return deltas;-};--// Sender-scoped for the same reason as `getTrailingReasoningDeltas` (#1656):-// a main-agent action must not strip the planning agent's live content.-const getTrailingContentDeltas = (- uiEvents: OpenHandsEvent[],- finalEvent: OpenHandsEvent,-) =>- getTrailingDeltas(- uiEvents,- (event) =>- (event.content?.length ?? 0) > 0 &&- isSameStreamingSender(finalEvent, event),+// `item_id` is a uuid, so the slot lookup needs no socket scoping.+const findSlotIndex = (uiEvents: UIEvent[], itemId: string): number =>+ uiEvents.findIndex(+ (event) => isStreamingDeltaEvent(event) && event.id === itemId,);-// Sender-scoped: the main and planning sockets share this event store, so a-// main-agent action must not strip the planning agent's live reasoning (#1656).-const getTrailingReasoningDeltas = (- uiEvents: OpenHandsEvent[],- finalEvent: OpenHandsEvent,-) =>- getTrailingDeltas(- uiEvents,+/**+ * Where a slot anchored after `anchorSeq` belongs: before the first event the+ * server sequenced after it. This is what keeps a user message that lands+ * mid-stream *below* the bubble instead of splitting it (#15433).+ *+ * `seq` is an index into *one* conversation's log, and the main and planning+ * sockets are different conversations whose logs both start at 0, so the scan+ * must stay inside the slot's own socket or it lands in the other's history.+ */+const slotInsertIndex = (+ uiEvents: UIEvent[],+ anchorSeq: number | null | undefined,+ isFromPlanningAgent: boolean,+): number => {+ if (anchorSeq === null || anchorSeq === undefined) {+ return uiEvents.length;+ }+ const index = uiEvents.findIndex((event) =>- Boolean(event.reasoning_content) &&- isSameStreamingSender(finalEvent, event),+ event.seq !== undefined &&+ isSameSocket(event, isFromPlanningAgent) &&+ event.seq > anchorSeq,);--// Strip the streamed content deltas, keeping a delta only when it carries-// reasoning the replacement itself won't render (many models stream reasoning-// solely through the delta). Shared by the finalize and intermediate-action-// reconciliation paths.-const supersedeStreamingContent = (- uiEvents: OpenHandsEvent[],- contentDeltas: { event: StreamingDeltaEvent; index: number }[],- replacementRendersReasoning: boolean,-): OpenHandsEvent[] => {- const indexesToStrip = new Set(contentDeltas.map(({ index }) => index));- const nextUiEvents: OpenHandsEvent[] = [];- uiEvents.forEach((event, index) => {- if (!indexesToStrip.has(index) || !isStreamingDeltaEvent(event)) {- nextUiEvents.push(event);- return;- }-- // Keep the delta only to render reasoning the replacement itself lacks.- if (!replacementRendersReasoning && event.reasoning_content) {- nextUiEvents.push({ ...event, content: null });- }- });- return nextUiEvents;+ return index === -1 ? uiEvents.length : index;};-// Whether the streamed `segments` (in order) reconcile against `targetText`.-// `lastMatchEnd` is the offset past the matched text, so callers can recover-// any not-yet-streamed suffix. The SDK strips the finalized text, so tolerate-// leading and trailing whitespace that appeared only in the stream.-const matchStreamedSegments = (- targetText: string,- segments: string[],-): { matched: boolean; lastMatchEnd: number } => {- const streamedText = segments.join("");- const candidates = new Set([- streamedText,- streamedText.trimEnd(),- streamedText.trimStart(),- streamedText.trim(),- ]);- for (const candidate of candidates) {- if (candidate && targetText.startsWith(candidate)) {- return { matched: true, lastMatchEnd: candidate.length };+/** The anchor event itself, or the nearest earlier event from the same socket. */+const findAnchor = (+ uiEvents: UIEvent[],+ anchorSeq: number | null | undefined,+ isFromPlanningAgent: boolean,+ insertIndex: number,+): UIEvent | undefined => {+ if (anchorSeq !== null && anchorSeq !== undefined) {+ const exact = uiEvents.find(+ (event) =>+ event.seq === anchorSeq && isSameSocket(event, isFromPlanningAgent),+ );+ if (exact) {+ return exact;}}- // Segments may be interleaved with not-yet-streamed text; locate them in- // order, trimming the last segment's trailing whitespace.- const lastIndex = segments.length - 1;- const searchSegments = segments.map((segment, index) =>- index === lastIndex ? segment.trimEnd() : segment,- );- return findTextSegmentsInOrder(targetText, searchSegments);-};--// A `<function=` marker means the delta still holds the raw prompted-tool-call-// XML the SDK strips only after the response completes, so the streamed text is-// a superset of the action's `thought` that `matchStreamedSegments` can't match.-const hasUnstrippedFunctionCallMarker = (segments: string[]): boolean =>- segments.some((segment) => segment.includes("<function="));--// Whether the finalized event renders its own reasoning: an ActionEvent via-// reasoning_content/thinking_blocks, an agent MessageEvent via an inline-// <think> block in its content. Decides if a replaced delta's reasoning must-// be preserved separately.-const eventRendersReasoning = (event: OpenHandsEvent): boolean => {- if (isActionEvent(event)) {- return getReasoningContent(event).trim().length > 0;+ // No `findLast` under lib es2022.+ for (let i = insertIndex - 1; i >= 0; i -= 1) {+ if (isSameSocket(uiEvents[i], isFromPlanningAgent)) {+ return uiEvents[i];+ }}+ return undefined;+};- if (isMessageEvent(event) && event.source === "agent") {- return (- splitInlineThink(joinTextBlocks(event.llm_message.content)).reasoning- .length > 0- );+/**+ * Open (or re-open, for a higher attempt) the slot an `item_started` frame+ * announces. A lower or equal attempt is ignored.+ */+export const openStreamingSlot = (+ frame: ItemStartedFrame,+ uiEvents: UIEvent[],+ meta: StreamingSlotMeta = {},+): UIEvent[] => {+ const attempt = frame.attempt ?? 1;+ const existingIndex = findSlotIndex(uiEvents, frame.item_id);++ if (existingIndex !== -1) {+ const slot = uiEvents[existingIndex] as StreamingDeltaEvent;+ // Only a higher attempt supersedes; a repeat of the current one is a no-op.+ if (attemptOf(slot) >= attempt) {+ return uiEvents;+ }+ const next = [...uiEvents];+ next[existingIndex] = {+ ...slot,+ attempt,+ content: null,+ reasoning_content: null,+ };+ return next;}- return false;-};--// The final MessageEvent/FinishAction is authoritative for the turn's text. Drop-// the provisional streamed deltas and render the canonical final event instead,-// so the message is rendered exactly once (never holey or duplicated) and its-// metadata β critic_result, activated_skills β renders too. Stream-only-// reasoning is preserved. Returns null when there is no streamed content to-// reconcile, leaving the caller to append the final event normally.-const finalizeStreamingDeltasInPlace = (- finalEvent: OpenHandsEvent,- uiEvents: OpenHandsEvent[],-): OpenHandsEvent[] | null => {- const contentStreamingDeltas = getCurrentTurnContentDeltas(+ const isFromPlanningAgent = Boolean(meta.isFromPlanningAgent);+ const insertIndex = slotInsertIndex(uiEvents,- finalEvent,+ frame.anchor_seq,+ isFromPlanningAgent,);- if (contentStreamingDeltas.length === 0) {- return null;- }-- const nextUiEvents = supersedeStreamingContent(+ // Borrow the anchor's timestamp so the store's timestamp sort β which fires+ // whenever durable frames arrive out of order, as they routinely do β keeps+ // the slot right after it. Prefer the anchor event itself: a neighbour may be+ // a client-stamped event whose clock does not match the server's.+ const anchor = findAnchor(uiEvents,- contentStreamingDeltas,- eventRendersReasoning(finalEvent),+ frame.anchor_seq,+ isFromPlanningAgent,+ insertIndex,);- nextUiEvents.push(finalEvent);- return nextUiEvents;+ const slot: StreamingDeltaEvent & StreamingSlotMeta = {+ kind: "StreamingDeltaEvent",+ id: frame.item_id,+ source: "agent",+ timestamp:+ anchor && "timestamp" in anchor && anchor.timestamp+ ? anchor.timestamp+ : new Date().toISOString(),+ content: null,+ reasoning_content: null,+ attempt,+ ...meta,+ };++ const next = [...uiEvents];+ next.splice(insertIndex, 0, slot);+ return next;};/**- * Reconcile the current turn's streaming delta when an intermediate- * (tool-calling) `ActionEvent` arrives. With `stream=true` the step's- * pre-tool-call text is streamed as delta `content`, then the action's- * `thought` repeats it and the chat hoists that into its own message (see- * `group-events.ts`), so the text would render twice (issue #1534).- *- * The action must stay because it owns the tool call. The streamed text is- * cleared from the delta, and the delta is kept only to carry reasoning the- * action itself lacks (for many models the delta is the sole reasoning- * carrier), otherwise dropped.+ * Append a batch of `delta` frames to their slots.*- * Only the current step's trailing delta run is considered. Returns the updated- * array, or `null` when there is nothing to reconcile.+ * A delta with no open slot opens one: its `item_started` went by before this+ * socket connected (progress frames are never replayed) β which is the normal+ * case for the first reply of a conversation started from the home page, since+ * the socket waits for the history load. This cannot orphan a bubble: slots+ * and buffered deltas are discarded on connect and disconnect, so the delta is+ * live on this connection, and the server retires every stream on it. The one+ * race β a delta overtaken by its own durable event, which travels a different+ * fan-out β is closed by `isFinished`.*/-const supersedeStreamedThoughtWithAction = (- action: ActionEvent,- uiEvents: OpenHandsEvent[],-): OpenHandsEvent[] | null => {- const thoughtText = joinTextBlocks(action.thought);- if (!thoughtText) {- return null;- }-- const contentDeltas = getTrailingContentDeltas(uiEvents, action);- if (contentDeltas.length === 0) {- return null;- }-- const streamingSegments = contentDeltas.map(- ({ event }) => event.content ?? "",- );-- // Strip on a thought match, or on an unstripped `<function=...>` marker whose- // streamed text is a superset of `thought` that the match can't reconcile.- const matchedThought = matchStreamedSegments(- thoughtText,- streamingSegments,- ).matched;- if (!matchedThought && !hasUnstrippedFunctionCallMarker(streamingSegments)) {- return null;+export const appendStreamingDeltas = (+ frames: DeltaFrame[],+ uiEvents: UIEvent[],+ {+ isFinished = () => false,+ ...meta+ }: StreamingSlotMeta & { isFinished?: (itemId: string) => boolean } = {},+): UIEvent[] => {+ let next = uiEvents;+ let copied = false;++ for (const frame of frames) {+ let index = findSlotIndex(next, frame.item_id);+ if (index === -1) {+ if (isFinished(frame.item_id)) {+ continue;+ }+ next = openStreamingSlot(+ {+ type: "item_started",+ item_id: frame.item_id,+ attempt: frame.attempt,+ },+ next,+ meta,+ );+ copied = true;+ index = findSlotIndex(next, frame.item_id);+ }+ const slot = next[index] as StreamingDeltaEvent;+ const attempt = frame.attempt ?? 1;+ if (attempt < attemptOf(slot)) {+ continue;+ }+ // A higher attempt re-streams the item, so the old tail is superseded.+ const superseded = attempt > attemptOf(slot);+ const content = superseded ? "" : (slot.content ?? "");+ const reasoning = superseded ? "" : (slot.reasoning_content ?? "");+ const isReasoning = frame.kind === "reasoning";++ if (!copied) {+ next = [...next];+ copied = true;+ }+ next[index] = {+ ...slot,+ attempt,+ content: (isReasoning ? content : content + frame.content) || null,+ reasoning_content:+ (isReasoning ? reasoning + frame.content : reasoning) || null,+ };}- // Keeping the delta's reasoning would duplicate the action's own "Thinking".- return supersedeStreamingContent(- uiEvents,- contentDeltas,- getReasoningContent(action).trim().length > 0,- );+ return next;};-// Drop the current step's streamed reasoning when the action renders that-// reasoning itself, so "Thinking" renders once. Unlike-// `supersedeStreamedThoughtWithAction` this does not require the streamed text-// to match the thought, which models streaming reasoning-only deltas never do.-const supersedeStreamedReasoningWithAction = (- action: ActionEvent,- uiEvents: OpenHandsEvent[],-): OpenHandsEvent[] | null => {- if (getReasoningContent(action).trim().length === 0) {- return null;+/**+ * Drop the slot for `itemId`. Used by `item_aborted`: the stream ended without+ * a durable event, so nothing is coming to supersede the provisional text.+ */+export const abortStreamingSlot = (+ itemId: string,+ uiEvents: UIEvent[],+ attempt?: number,+): UIEvent[] => {+ const index = findSlotIndex(uiEvents, itemId);+ if (index === -1) {+ return uiEvents;}-- const reasoningDeltas = getTrailingReasoningDeltas(uiEvents, action);- if (reasoningDeltas.length === 0) {- return null;+ // An abort for a superseded attempt must not delete the live retry's slot.+ if (+ attempt !== undefined &&+ attempt < attemptOf(uiEvents[index] as StreamingDeltaEvent)+ ) {+ return uiEvents;}+ return uiEvents.filter((_, position) => position !== index);+};- const indexesToStrip = new Set(reasoningDeltas.map(({ index }) => index));- const nextUiEvents: OpenHandsEvent[] = [];- uiEvents.forEach((event, index) => {- if (!indexesToStrip.has(index) || !isStreamingDeltaEvent(event)) {- nextUiEvents.push(event);- return;- }-- // Keep the delta only for streamed text the action itself lacks.- if (event.content) {- nextUiEvents.push({ ...event, reasoning_content: null });- }- });- return nextUiEvents;+/**+ * Drop every open slot for one socket. Called on connect and disconnect:+ * progress frames are never replayed, so an open slot cannot survive the gap,+ * and the message it was standing in for arrives on the durable cursor.+ */+export const clearStreamingSlots = (+ uiEvents: UIEvent[],+ isFromPlanningAgent = false,+): UIEvent[] => {+ const next = uiEvents.filter(+ (event) =>+ !isStreamingDeltaEvent(event) ||+ !isSameSocket(event as UIEvent, isFromPlanningAgent),+ );+ return next.length === uiEvents.length ? uiEvents : next;};/**@@ -346,59 +271,21 @@ const supersedeStreamedReasoningWithAction = (* its action below.*/export const handleEventForUI = (- event: OpenHandsEvent,- uiEvents: OpenHandsEvent[],-): OpenHandsEvent[] => {+ event: UIEvent,+ uiEvents: UIEvent[],+): UIEvent[] => {const newUiEvents = [...uiEvents];- if (isStreamingDeltaEvent(event)) {- if (event.content === null && event.reasoning_content === null) {+ // The durable event *is* the item: the SDK mints its id when the stream+ // opens, so one equality test retires the slot β and replacing in place+ // keeps the finished message where the streamed text already was.+ const eventId = "id" in event ? event.id : undefined;+ if (eventId !== undefined) {+ const slotIndex = findSlotIndex(newUiEvents, eventId);+ if (slotIndex !== -1) {+ newUiEvents[slotIndex] = event;return newUiEvents;}-- const lastIndex = newUiEvents.length - 1;- const lastEvent = newUiEvents[lastIndex];- if (- lastEvent &&- isStreamingDeltaEvent(lastEvent) &&- isSameStreamingSender(event, lastEvent)- ) {- newUiEvents[lastIndex] = mergeStreamingDeltaEvent(event, lastEvent);- return newUiEvents;- }-- newUiEvents.push(event);- return newUiEvents;- }-- if (- (isActionEvent(event) && event.action.kind === "FinishAction") ||- (isMessageEvent(event) && event.source === "agent")- ) {- const finalizedUiEvents = finalizeStreamingDeltasInPlace(- event,- newUiEvents,- );- if (finalizedUiEvents) {- return finalizedUiEvents;- }- }-- // Intermediate tool-calling action whose thought was streamed: clear the- // duplicated text from the delta (issue #1534). ThinkAction is excluded β its- // thought renders through its own collapsible, not a hoisted thought.- if (- isActionEvent(event) &&- event.action.kind !== "FinishAction" &&- event.action.kind !== "ThinkAction"- ) {- const reconciledUiEvents =- supersedeStreamedThoughtWithAction(event, newUiEvents) ??- supersedeStreamedReasoningWithAction(event, newUiEvents);- if (reconciledUiEvents) {- reconciledUiEvents.push(event);- return reconciledUiEvents;- }}if (isACPToolCallEvent(event)) {diff --git a/src/utils/session-seq-cursor.ts b/src/utils/session-seq-cursor.tsnew file mode 100644index 0000000000..44fcc42329--- /dev/null+++ b/src/utils/session-seq-cursor.ts@@ -0,0 +1,63 @@+/**+ * Resume cursor for `/sockets/session/{id}`.+ *+ * Durable frames are not delivered in `seq` order β a state update can overtake+ * the message persisted just before it β so resuming from the highest seq seen+ * would skip whatever was still in flight when the socket dropped. The cursor+ * is instead the highest seq with nothing missing below it.+ */+export interface SeqCursor {+ /** Highest seq with no gap below it, or `null` before the first connect. */+ readonly value: number | null;+ /** Begin a connection that replays everything after `base`. */+ start: (base: number) => void;+ observe: (seq: number) => void;+ clear: () => void;+}++/**+ * How far past a gap to wait before stepping over it. The server skips events+ * it cannot read, and that seq never arrives β on this connection or any+ * later one β so an unbounded wait would freeze the cursor at the hole and+ * replay from it on every reconnect.+ */+const MAX_AHEAD = 1024;++export function createSeqCursor(): SeqCursor {+ let value: number | null = null;+ let ahead = new Set<number>();++ const drain = () => {+ while (value !== null && ahead.has(value + 1)) {+ value += 1;+ ahead.delete(value);+ }+ };++ return {+ get value() {+ return value;+ },+ start: (base) => {+ value = base;+ // Anything seen past a gap is replayed on this connection and deduped.+ ahead = new Set();+ },+ observe: (seq) => {+ if (value === null || seq <= value) {+ return;+ }+ ahead.add(seq);+ drain();+ if (ahead.size > MAX_AHEAD) {+ // Step over the hole: the skipped event is unreadable on replay too.+ value = Math.min(...ahead) - 1;+ drain();+ }+ },+ clear: () => {+ value = null;+ ahead = new Set();+ },+ };+}diff --git a/src/utils/streaming-delta-batcher.ts b/src/utils/streaming-delta-batcher.tsindex f0231f8027..80941b404d 100644--- a/src/utils/streaming-delta-batcher.ts+++ b/src/utils/streaming-delta-batcher.ts@@ -1,5 +1,4 @@-import { StreamingDeltaEvent } from "#/types/agent-server/core/events/streaming-delta-event";-import { mergeStreamingDeltaEvent } from "#/utils/handle-event-for-ui";+import type { DeltaFrame } from "#/types/agent-server/session-frames";/** Schedules a single deferred callback (defaults to the animation frame). */export interface DeltaFlushScheduler {@@ -19,25 +18,25 @@ const defaultScheduler: DeltaFlushScheduler =};export interface StreamingDeltaBatcher {- /** Buffer a delta; a flush is scheduled for the next frame if not already. */- enqueue: (event: StreamingDeltaEvent) => void;- /** Commit buffered deltas now. Call before any non-delta event. */+ /** Buffer a delta frame; a flush is scheduled for the next frame if not already. */+ enqueue: (frame: DeltaFrame) => void;+ /** Commit buffered deltas now. Call before any other frame. */flush: () => void;/** Drop buffered deltas without committing. Call on unmount / conversation switch. */reset: () => void;}/**- * Coalesces adjacent `StreamingDeltaEvent`s and commits them at most once per- * animation frame, so a fast model can't force a store commit + re-render per- * token. Callers MUST `flush()` before any non-delta event so a- * durable message/action can't render ahead of its own streamed text.+ * Commits buffered `delta` frames at most once per animation frame, so a fast+ * model can't force a store commit + re-render per token. Callers MUST+ * `flush()` before any other frame so an `item_started`, an abort or a durable+ * message can't overtake text that was streamed ahead of it.*/export function createStreamingDeltaBatcher(- commit: (event: StreamingDeltaEvent) => void,+ commit: (frames: DeltaFrame[]) => void,scheduler: DeltaFlushScheduler = defaultScheduler,): StreamingDeltaBatcher {- let pending: StreamingDeltaEvent[] = [];+ let pending: DeltaFrame[] = [];let frame: number | null = null;const cancelFrame = () => {@@ -54,14 +53,12 @@ export function createStreamingDeltaBatcher(}const batch = pending;pending = [];- commit(- batch.reduce((merged, delta) => mergeStreamingDeltaEvent(delta, merged)),- );+ commit(batch);};return {- enqueue: (event) => {- pending.push(event);+ enqueue: (incoming) => {+ pending.push(incoming);if (frame === null) {frame = scheduler.schedule(flush);}diff --git a/src/utils/websocket-url.ts b/src/utils/websocket-url.tsindex 6abd9cd581..c9e8883036 100644--- a/src/utils/websocket-url.ts+++ b/src/utils/websocket-url.ts@@ -95,7 +95,9 @@ export function buildWebSocketUrl(const baseHost = extractBaseHost(conversationUrl);const pathPrefix = extractPathPrefix(conversationUrl);- // Build WebSocket URL: ws://host:port[/path-prefix]/sockets/events/{conversationId}+ // Build WebSocket URL: ws://host:port[/path-prefix]/sockets/session/{conversationId}+ // The session endpoint speaks the envelope protocol (durable events plus+ // stream-progress frames); the legacy /sockets/events endpoint is frozen.// The path prefix (e.g., /runtime/55313) is needed for proxy deployments// Note: Query params should be passed via the useWebSocket hook options//@@ -109,5 +111,5 @@ export function buildWebSocketUrl(getConversationUrlProtocol(conversationUrl) === "https:";const protocol = pageIsSecure || targetIsSecure ? "wss:" : "ws:";- return `${protocol}//${baseHost}${pathPrefix}/sockets/events/${conversationId}`;+ return `${protocol}//${baseHost}${pathPrefix}/sockets/session/${conversationId}`;}