Skip to content

🙌 OpenHands: AI-Driven Development

fix: stream LLM tokens for cloud conversations and profile switches (#15021)

Vasco Schiavoc105a8238789
diff --git a/frontend/__tests__/utils/handle-event-for-ui.test.ts b/frontend/__tests__/utils/handle-event-for-ui.test.ts
index e9b8ae5608..f4aa7b5052 100644
--- a/frontend/__tests__/utils/handle-event-for-ui.test.ts
+++ b/frontend/__tests__/utils/handle-event-for-ui.test.ts
@@ -7,7 +7,9 @@ import {
OpenHandsEvent,
} from "#/types/v1/core";
import { ACPToolCallEvent } from "#/types/v1/core/events/acp-tool-call-event";
+import { StreamingDeltaEvent } from "#/types/v1/core/events/streaming-delta-event";
import { handleEventForUI } from "#/utils/handle-event-for-ui";
+import { isStreamingDeltaEvent } from "#/types/v1/type-guards";
describe("handleEventForUI", () => {
const mockObservationEvent: ObservationEvent = {
@@ -263,3 +265,123 @@ describe("handleEventForUI", () => {
expect(result).not.toBe(initialUiEvents);
});
});
+
+describe("handleEventForUI - streaming deltas", () => {
+ let nextId = 0;
+ const delta = (
+ content: string | null,
+ reasoning_content: string | null = null,
+ ): StreamingDeltaEvent => {
+ nextId += 1;
+ return {
+ id: `delta-${nextId}`,
+ timestamp: `2026-06-29T00:00:0${nextId}.000Z`,
+ source: "agent",
+ kind: "StreamingDeltaEvent",
+ content,
+ reasoning_content,
+ };
+ };
+
+ const userMessage: MessageEvent = {
+ id: "user-1",
+ timestamp: "2026-06-29T00:00:00.000Z",
+ source: "user",
+ llm_message: { role: "user", content: [{ type: "text", text: "hi" }] },
+ activated_microagents: [],
+ extended_content: [],
+ };
+
+ const assistantMessage = (text: string): MessageEvent => ({
+ id: "assistant-1",
+ timestamp: "2026-06-29T00:00:09.000Z",
+ source: "agent",
+ llm_message: { role: "assistant", content: [{ type: "text", text }] },
+ activated_microagents: [],
+ extended_content: [],
+ });
+
+ const stateUpdate = (id: string): OpenHandsEvent =>
+ ({
+ id,
+ timestamp: "2026-06-29T00:00:05.500Z",
+ source: "environment",
+ kind: "ConversationStateUpdateEvent",
+ key: "stats",
+ value: {},
+ }) as unknown as OpenHandsEvent;
+
+ it("merges consecutive deltas into one growing bubble keeping the first id", () => {
+ let ui: OpenHandsEvent[] = [userMessage];
+ const first = delta("Hello");
+ ui = handleEventForUI(first, ui);
+ ui = handleEventForUI(delta(", "), ui);
+ ui = handleEventForUI(delta("world"), ui);
+
+ expect(ui).toHaveLength(2);
+ const merged = ui[1];
+ expect(isStreamingDeltaEvent(merged)).toBe(true);
+ expect((merged as StreamingDeltaEvent).content).toBe("Hello, world");
+ expect(merged.id).toBe(first.id);
+ });
+
+ it("merges deltas into one bubble even when a state update interleaves", () => {
+ let ui: OpenHandsEvent[] = [userMessage];
+ const first = delta("Hello");
+ ui = handleEventForUI(first, ui);
+ ui = handleEventForUI(stateUpdate("state-1"), ui);
+ ui = handleEventForUI(delta(", world"), ui);
+
+ const deltas = ui.filter(isStreamingDeltaEvent) as StreamingDeltaEvent[];
+ expect(deltas).toHaveLength(1);
+ expect(deltas[0].content).toBe("Hello, world");
+ expect(deltas[0].id).toBe(first.id);
+ });
+
+ it("concatenates reasoning_content across deltas", () => {
+ let ui: OpenHandsEvent[] = [userMessage];
+ ui = handleEventForUI(delta(null, "think "), ui);
+ ui = handleEventForUI(delta(null, "more"), ui);
+
+ expect(ui).toHaveLength(2);
+ expect((ui[1] as StreamingDeltaEvent).reasoning_content).toBe("think more");
+ });
+
+ it("drops empty boundary deltas that carry no text", () => {
+ const ui = handleEventForUI(delta(null, null), [userMessage]);
+ expect(ui).toEqual([userMessage]);
+ });
+
+ it("reconciles the final assistant message into the delta without duplicating the bubble", () => {
+ let ui: OpenHandsEvent[] = [userMessage];
+ const first = delta("Hello");
+ ui = handleEventForUI(first, ui);
+ ui = handleEventForUI(delta(", world"), ui);
+ ui = handleEventForUI(assistantMessage("Hello, world"), ui);
+
+ expect(ui).toHaveLength(2); // user message + the (reconciled) delta bubble
+ const finalBubble = ui[1];
+ expect(isStreamingDeltaEvent(finalBubble)).toBe(true);
+ expect((finalBubble as StreamingDeltaEvent).content).toBe("Hello, world");
+ expect(finalBubble.id).toBe(first.id);
+ });
+
+ it("appends the final message's unstreamed suffix to the last delta", () => {
+ let ui: OpenHandsEvent[] = [userMessage];
+ ui = handleEventForUI(delta("Hel"), ui);
+ // The provider buffered the tail: final text has content never streamed.
+ ui = handleEventForUI(assistantMessage("Hello, world"), ui);
+
+ expect(ui).toHaveLength(2);
+ expect((ui[1] as StreamingDeltaEvent).content).toBe("Hello, world");
+ });
+
+ it("appends the final message normally when nothing was streamed (stream=False)", () => {
+ const final = assistantMessage("Complete answer");
+ const ui = handleEventForUI(final, [userMessage]);
+
+ expect(ui).toHaveLength(2);
+ expect(ui[1]).toBe(final);
+ expect(isStreamingDeltaEvent(ui[1])).toBe(false);
+ });
+});
diff --git a/frontend/src/components/v1/chat/event-content-helpers/should-render-event.ts b/frontend/src/components/v1/chat/event-content-helpers/should-render-event.ts
index 9d977f6042..1f1f411c46 100644
--- a/frontend/src/components/v1/chat/event-content-helpers/should-render-event.ts
+++ b/frontend/src/components/v1/chat/event-content-helpers/should-render-event.ts
@@ -8,6 +8,7 @@ import {
isConversationStateUpdateEvent,
isHookExecutionEvent,
isACPToolCallEvent,
+ isStreamingDeltaEvent,
isV1Event,
} from "#/types/v1/type-guards";
@@ -49,6 +50,12 @@ export const shouldRenderEvent = (event: OpenHandsEvent) => {
return true;
}
+ // Render streaming token deltas (the live, growing assistant bubble).
+ // Empty boundary deltas are dropped upstream in handleEventForUI.
+ if (isStreamingDeltaEvent(event)) {
+ return true;
+ }
+
// Render agent error events
if (isAgentErrorEvent(event)) {
return true;
diff --git a/frontend/src/components/v1/chat/event-message.tsx b/frontend/src/components/v1/chat/event-message.tsx
index 1dfb6c26bf..7616bc938c 100644
--- a/frontend/src/components/v1/chat/event-message.tsx
+++ b/frontend/src/components/v1/chat/event-message.tsx
@@ -1,6 +1,8 @@
import React from "react";
+import { useTranslation } from "react-i18next";
import { OpenHandsEvent, MessageEvent, ActionEvent } from "#/types/v1/core";
import { FinishAction, ThinkAction } from "#/types/v1/core/base/action";
+import { I18nKey } from "#/i18n/declaration";
import {
isActionEvent,
isObservationEvent,
@@ -9,12 +11,14 @@ import {
isPlanningFileEditorObservationEvent,
isHookExecutionEvent,
isACPToolCallEvent,
+ isStreamingDeltaEvent,
} from "#/types/v1/type-guards";
import { useConfig } from "#/hooks/query/use-config";
import { useConversationStore } from "#/stores/conversation-store";
import { useAgentState } from "#/hooks/use-agent-state";
import { AgentState } from "#/types/agent-state";
import { ChatMessage } from "../../features/chat/chat-message";
+import { GenericEventMessage } from "../../features/chat/generic-event-message";
import { PlanPreview } from "../../features/chat/plan-preview";
import {
ErrorEventMessage,
@@ -123,6 +127,7 @@ export function EventMessage({
isInLast10Actions,
planPreviewEventIds,
}: EventMessageProps) {
+ const { t } = useTranslation();
const { data: config } = useConfig();
const { planContent } = useConversationStore();
const { curAgentState } = useAgentState();
@@ -162,6 +167,36 @@ export function EventMessage({
);
}
+ // Streaming token deltas - the live, growing assistant bubble. Consecutive
+ // deltas are merged upstream (handleEventForUI / event store) into this single
+ // event, and the turn's final MessageEvent is reconciled into it rather than
+ // appended, so this same bubble becomes the finalized message.
+ if (isStreamingDeltaEvent(event)) {
+ const reasoning = event.reasoning_content ?? "";
+ const message = event.content ?? "";
+ return (
+ <>
+ {reasoning && (
+ // Render the streamed reasoning as a collapsible "Thinking" section
+ // (collapsed by default) so it's distinct from the answer and doesn't
+ // dominate the bubble.
+ <GenericEventMessage
+ title={t(I18nKey.EVENT$THINKING)}
+ details={reasoning}
+ initiallyExpanded={false}
+ />
+ )}
+ {message && (
+ <ChatMessage
+ type="agent"
+ message={message}
+ isFromPlanningAgent={isFromPlanningAgent}
+ />
+ )}
+ </>
+ );
+ }
+
// Finish actions
if (isActionEvent(event) && event.action.kind === "FinishAction") {
return (
diff --git a/frontend/src/components/v1/chat/messages.tsx b/frontend/src/components/v1/chat/messages.tsx
index aa8fb102c1..69fc41349b 100644
--- a/frontend/src/components/v1/chat/messages.tsx
+++ b/frontend/src/components/v1/chat/messages.tsx
@@ -80,14 +80,12 @@ export const Messages: React.FC<MessagesProps> = React.memo(
</>
);
},
- (prevProps, nextProps) => {
- // Prevent re-renders if messages are the same length
- if (prevProps.messages.length !== nextProps.messages.length) {
- return false;
- }
-
- return true;
- },
+ // Default shallow prop comparison: re-render whenever the `messages`/`allEvents`
+ // array reference changes (a fresh array is produced whenever the event store
+ // updates). A custom length-only comparator was previously used, but it
+ // skipped re-renders when a streaming delta grows its bubble *in place*
+ // (content changes, array length stays the same), so the live answer never
+ // repainted until the next event changed the length.
);
Messages.displayName = "Messages";
diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.ts
index ae4737f74b..77fd0fe2f4 100644
--- a/frontend/src/i18n/declaration.ts
+++ b/frontend/src/i18n/declaration.ts
@@ -43,6 +43,7 @@ export enum I18nKey {
FINISH$TASK_NOT_COMPLETED = "FINISH$TASK_NOT_COMPLETED",
FINISH$TASK_COMPLETED_PARTIALLY = "FINISH$TASK_COMPLETED_PARTIALLY",
EVENT$UNKNOWN_EVENT = "EVENT$UNKNOWN_EVENT",
+ EVENT$THINKING = "EVENT$THINKING",
OBSERVATION$COMMAND_NO_OUTPUT = "OBSERVATION$COMMAND_NO_OUTPUT",
OBSERVATION$MCP_NO_OUTPUT = "OBSERVATION$MCP_NO_OUTPUT",
OBSERVATION$TASK_TRACKING_NO_OUTPUT = "OBSERVATION$TASK_TRACKING_NO_OUTPUT",
diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.json
index b21311ebb8..dfc44b4f00 100644
--- a/frontend/src/i18n/translation.json
+++ b/frontend/src/i18n/translation.json
@@ -730,6 +730,23 @@
"uk": "Невідома подія",
"ca": "Esdeveniment desconegut"
},
+ "EVENT$THINKING": {
+ "en": "Thinking",
+ "ja": "思考中",
+ "zh-CN": "思考中",
+ "zh-TW": "思考中",
+ "ko-KR": "생각 중",
+ "no": "Tenker",
+ "it": "Ragionamento",
+ "pt": "Raciocínio",
+ "es": "Razonamiento",
+ "ar": "التفكير",
+ "fr": "Réflexion",
+ "tr": "Düşünme",
+ "de": "Nachdenken",
+ "uk": "Міркування",
+ "ca": "Raonament"
+ },
"OBSERVATION$COMMAND_NO_OUTPUT": {
"en": "[Command finished execution with no output]",
"ja": "[コマンドは出力なしで実行を終了しました]",
diff --git a/frontend/src/stores/use-event-store.ts b/frontend/src/stores/use-event-store.ts
index 2dfc66e37e..d1db847b34 100644
--- a/frontend/src/stores/use-event-store.ts
+++ b/frontend/src/stores/use-event-store.ts
@@ -1,8 +1,11 @@
import { create } from "zustand";
import { OpenHandsEvent } from "#/types/v1/core";
-import { handleEventForUI } from "#/utils/handle-event-for-ui";
+import {
+ handleEventForUI,
+ mergeStreamingDeltaEvent,
+} from "#/utils/handle-event-for-ui";
import { OpenHandsParsedEvent } from "#/types/core";
-import { isV1Event } from "#/types/v1/type-guards";
+import { isStreamingDeltaEvent, isV1Event } from "#/types/v1/type-guards";
// While we transition to v1 events, our store can handle both v0 and v1 events
export type OHEvent = (OpenHandsEvent | OpenHandsParsedEvent) & {
@@ -70,8 +73,28 @@ export const useEventStore = create<EventState>()((set) => ({
return state;
}
- // Add event and sort if needed to maintain chronological order
- let newEvents = [...state.events, event];
+ // Merge consecutive streaming token deltas into a single growing entry
+ // (keeping the first delta's id) so the durable log isn't flooded with one
+ // entry per token. Deltas must stay in `events`: the chat passes this list
+ // as `allEvents` for lookups, and a delta missing from it renders empty.
+ // Non-delta events append normally.
+ const lastEvent = state.events[state.events.length - 1];
+ let newEvents: OHEvent[];
+ if (
+ lastEvent &&
+ isV1Event(event) &&
+ isV1Event(lastEvent) &&
+ isStreamingDeltaEvent(event) &&
+ isStreamingDeltaEvent(lastEvent)
+ ) {
+ newEvents = [...state.events];
+ newEvents[newEvents.length - 1] = mergeStreamingDeltaEvent(
+ event,
+ lastEvent,
+ );
+ } else {
+ newEvents = [...state.events, event];
+ }
if (needsSorting(state.events, event)) {
newEvents = newEvents.sort(compareEventsByTimestamp);
}
diff --git a/frontend/src/types/v1/core/events/index.ts b/frontend/src/types/v1/core/events/index.ts
index 08740d1132..f74a1fcb2a 100644
--- a/frontend/src/types/v1/core/events/index.ts
+++ b/frontend/src/types/v1/core/events/index.ts
@@ -7,4 +7,5 @@ export * from "./hook-execution-event";
export * from "./message-event";
export * from "./observation-event";
export * from "./pause-event";
+export * from "./streaming-delta-event";
export * from "./system-event";
diff --git a/frontend/src/types/v1/core/events/streaming-delta-event.ts b/frontend/src/types/v1/core/events/streaming-delta-event.ts
new file mode 100644
index 0000000000..421ad6b35e
--- /dev/null
+++ b/frontend/src/types/v1/core/events/streaming-delta-event.ts
@@ -0,0 +1,22 @@
+import { BaseEvent } from "../base/event";
+
+/**
+ * Transient LLM token delta emitted while the agent's LLM streams a response
+ * (when the LLM has ``stream=True``).
+ *
+ * These events are NOT part of the durable conversation record: the agent
+ * server publishes them straight to its WebSocket subscribers and never
+ * persists them. A client that reconnects mid-stream receives the final
+ * ``MessageEvent`` from history but none of the deltas that produced it — they
+ * are purely a live-rendering affordance. Consecutive deltas are merged in the
+ * event store, and reconciled into (then superseded by) the final
+ * ``MessageEvent`` / ``FinishAction`` for the turn.
+ */
+export interface StreamingDeltaEvent extends BaseEvent {
+ kind: "StreamingDeltaEvent";
+ source: "agent";
+ /** Incremental chunk of the assistant's user-facing message text. */
+ content: string | null;
+ /** Incremental chunk of the LLM's reasoning/thinking text. */
+ reasoning_content: string | null;
+}
diff --git a/frontend/src/types/v1/core/openhands-event.ts b/frontend/src/types/v1/core/openhands-event.ts
index 4eaa250507..fbb308566d 100644
--- a/frontend/src/types/v1/core/openhands-event.ts
+++ b/frontend/src/types/v1/core/openhands-event.ts
@@ -15,6 +15,7 @@ import {
HookExecutionEvent,
PauseEvent,
ServerErrorEvent,
+ StreamingDeltaEvent,
} from "./events/index";
/**
@@ -31,6 +32,8 @@ export type OpenHandsEvent =
| SystemPromptEvent
// ACP sub-agent tool call events
| ACPToolCallEvent
+ // Transient LLM token streaming deltas
+ | StreamingDeltaEvent
// Hook events
| HookExecutionEvent
// Conversation management events
diff --git a/frontend/src/types/v1/type-guards.ts b/frontend/src/types/v1/type-guards.ts
index a75fc69e4b..0a529f1c22 100644
--- a/frontend/src/types/v1/type-guards.ts
+++ b/frontend/src/types/v1/type-guards.ts
@@ -24,6 +24,7 @@ import {
} from "./core/events/conversation-state-event";
import { HookExecutionEvent } from "./core/events/hook-execution-event";
import { ACPToolCallEvent } from "./core/events/acp-tool-call-event";
+import { StreamingDeltaEvent } from "./core/events/streaming-delta-event";
import { SystemPromptEvent } from "./core/events/system-event";
import type { OpenHandsParsedEvent } from "../core/index";
@@ -237,6 +238,15 @@ export const isACPToolCallEvent = (
): event is ACPToolCallEvent =>
"kind" in event && event.kind === "ACPToolCallEvent";
+/**
+ * Type guard function to check if an event is a streaming token delta event
+ * (a transient LLM token chunk emitted while the response streams).
+ */
+export const isStreamingDeltaEvent = (
+ event: OpenHandsEvent,
+): event is StreamingDeltaEvent =>
+ "kind" in event && event.kind === "StreamingDeltaEvent";
+
// =============================================================================
// TEMPORARY COMPATIBILITY TYPE GUARDS
// These will be removed once we fully migrate to V1 events
diff --git a/frontend/src/utils/handle-event-for-ui.ts b/frontend/src/utils/handle-event-for-ui.ts
index b67023ad83..c06cbcab38 100644
--- a/frontend/src/utils/handle-event-for-ui.ts
+++ b/frontend/src/utils/handle-event-for-ui.ts
@@ -1,11 +1,185 @@
-import { OpenHandsEvent } from "#/types/v1/core";
-import { isACPToolCallEvent, isObservationEvent } from "#/types/v1/type-guards";
+import { MessageEvent, OpenHandsEvent } from "#/types/v1/core";
+import { StreamingDeltaEvent } from "#/types/v1/core/events/streaming-delta-event";
+import {
+ isACPToolCallEvent,
+ isActionEvent,
+ isConversationStateUpdateEvent,
+ isMessageEvent,
+ isObservationEvent,
+ isStreamingDeltaEvent,
+ isUserMessageEvent,
+} from "#/types/v1/type-guards";
+
+/**
+ * Concatenate two streaming deltas into one. Token chunks join directly with no
+ * separator. Keeps the *existing* delta's identity (id/timestamp) so the
+ * rendered bubble has a stable React key as it grows.
+ */
+export const mergeStreamingDeltaEvent = (
+ incoming: StreamingDeltaEvent,
+ existing: StreamingDeltaEvent,
+): StreamingDeltaEvent => ({
+ ...existing,
+ content: `${existing.content ?? ""}${incoming.content ?? ""}` || null,
+ reasoning_content:
+ `${existing.reasoning_content ?? ""}${incoming.reasoning_content ?? ""}` ||
+ null,
+});
+
+const appendContentToStreamingDeltaEvent = (
+ existing: StreamingDeltaEvent,
+ content: string,
+): StreamingDeltaEvent => ({
+ ...existing,
+ content: `${existing.content ?? ""}${content}` || null,
+});
+
+const findLastUserMessageIndex = (events: OpenHandsEvent[]): number => {
+ for (let index = events.length - 1; index >= 0; index -= 1) {
+ if (isUserMessageEvent(events[index])) {
+ return index;
+ }
+ }
+ return -1;
+};
+
+// 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 MessageEvent against the already-rendered streaming delta.
+const getAgentMessageText = (event: MessageEvent): string =>
+ event.llm_message.content
+ .filter((content) => content.type === "text")
+ .map((content) => content.text)
+ .join("");
+
+const getFinalAgentText = (event: OpenHandsEvent): string | null => {
+ if (isActionEvent(event) && event.action.kind === "FinishAction") {
+ return event.action.message;
+ }
+
+ if (isMessageEvent(event) && event.llm_message.role === "assistant") {
+ return getAgentMessageText(event);
+ }
+
+ return null;
+};
+
+const findTextSegmentsInOrder = (
+ text: string,
+ segments: string[],
+): { matched: boolean; lastMatchEnd: number } => {
+ let searchStart = 0;
+ let lastMatchEnd = 0;
+
+ for (const segment of segments) {
+ const index = text.indexOf(segment, searchStart);
+ if (index === -1) {
+ return { matched: false, lastMatchEnd };
+ }
+ lastMatchEnd = index + segment.length;
+ searchStart = lastMatchEnd;
+ }
+
+ return { matched: true, lastMatchEnd };
+};
+
+/**
+ * When the final agent message (a ``FinishAction`` or an assistant
+ * ``MessageEvent``) arrives, fold it into the streaming deltas that produced it
+ * instead of appending a duplicate bubble. The last content-bearing delta
+ * (extended with any text that only arrived in the final event) becomes the
+ * canonical rendered message for the turn.
+ *
+ * Returns the updated uiEvents (with the final event intentionally NOT appended)
+ * when there are content-bearing deltas for the current turn that reconcile
+ * against the final text; otherwise returns ``null`` so the caller appends the
+ * final event normally (e.g. non-streamed responses, or reasoning-only deltas).
+ */
+const finalizeStreamingDeltasInPlace = (
+ finalEvent: OpenHandsEvent,
+ uiEvents: OpenHandsEvent[],
+): OpenHandsEvent[] | null => {
+ const lastUserMessageIndex = findLastUserMessageIndex(uiEvents);
+ const currentTurnStreamingDeltaIndexes = uiEvents
+ .map((uiEvent, index) => ({ uiEvent, index }))
+ .filter(
+ ({ uiEvent, index }) =>
+ index > lastUserMessageIndex && isStreamingDeltaEvent(uiEvent),
+ )
+ .map(({ index }) => index);
+
+ if (currentTurnStreamingDeltaIndexes.length === 0) {
+ return null;
+ }
+
+ const finalText = getFinalAgentText(finalEvent);
+ // Only the regular `content` field participates in reconciliation.
+ // Reasoning-only deltas (those that carry only `reasoning_content`) produce
+ // an empty streamingSegments list, causing the function to return null so the
+ // finalEvent is appended normally. This is intentional: reasoning content
+ // renders in its own block and never overlaps with the assistant's regular
+ // message text.
+ const contentStreamingDeltas = currentTurnStreamingDeltaIndexes
+ .map((index) => ({ event: uiEvents[index], index }))
+ .filter(
+ (item): item is { event: StreamingDeltaEvent; index: number } =>
+ isStreamingDeltaEvent(item.event) &&
+ (item.event.content?.length ?? 0) > 0,
+ );
+ const streamingSegments = contentStreamingDeltas.map(
+ ({ event }) => event.content ?? "",
+ );
+
+ if (!finalText || streamingSegments.length === 0) {
+ return null;
+ }
+
+ const nextUiEvents = [...uiEvents];
+ const streamedText = streamingSegments.join("");
+ let unstreamedSuffix = "";
+
+ if (finalText.startsWith(streamedText)) {
+ unstreamedSuffix = finalText.slice(streamedText.length);
+ } else {
+ const match = findTextSegmentsInOrder(finalText, streamingSegments);
+ if (!match.matched) {
+ return null;
+ }
+ unstreamedSuffix = finalText.slice(match.lastMatchEnd);
+ }
+
+ const lastDeltaIndex = contentStreamingDeltas.at(-1)?.index;
+ const lastDelta =
+ lastDeltaIndex === undefined ? undefined : nextUiEvents[lastDeltaIndex];
+ if (
+ unstreamedSuffix &&
+ lastDeltaIndex !== undefined &&
+ lastDelta &&
+ isStreamingDeltaEvent(lastDelta)
+ ) {
+ nextUiEvents[lastDeltaIndex] = appendContentToStreamingDeltaEvent(
+ lastDelta,
+ unstreamedSuffix,
+ );
+ }
+
+ // Intentionally return nextUiEvents WITHOUT appending finalEvent. The last
+ // content-bearing streaming delta (possibly extended with unstreamedSuffix
+ // above) is the canonical final rendered bubble for this turn. Appending
+ // finalEvent here would display the assistant message twice.
+ return nextUiEvents;
+};
/**
* Handles adding an event to the UI events array
* Replaces actions with observations when they arrive (so UI shows observation instead of action)
* Exception: ThinkAction is NOT replaced because the thought content is in the action, not in the observation
*
+ * StreamingDeltaEvent: consecutive deltas merge in place into a single growing
+ * bubble; when the turn's final agent message arrives it is reconciled into that
+ * bubble (see `finalizeStreamingDeltasInPlace`) rather than appended.
+ *
* ACPToolCallEvent dedup: multiple events share a ``tool_call_id`` as an ACP
* tool call progresses (in_progress → completed / failed). Collapse them to
* the latest state at the original position so the card updates in place.
@@ -16,6 +190,59 @@ export const handleEventForUI = (
): OpenHandsEvent[] => {
const newUiEvents = [...uiEvents];
+ if (isStreamingDeltaEvent(event)) {
+ // Drop empty boundary deltas (e.g. after a tool call) that carry no text.
+ if (event.content === null && event.reasoning_content === null) {
+ return newUiEvents;
+ }
+
+ // Merge into the most recent streaming delta, treating interleaved non-chat
+ // events as transparent: the agent server emits periodic
+ // ConversationStateUpdateEvents (metrics) mid-stream, and those land in
+ // uiEvents between deltas. Stopping the search at the very last event would
+ // fragment one streamed response into several bubbles. A genuine rendered
+ // event (message/action/observation) does end the run, so subsequent deltas
+ // correctly start a fresh bubble.
+ let mergeIndex = -1;
+ for (let i = newUiEvents.length - 1; i >= 0; i -= 1) {
+ const candidate = newUiEvents[i];
+ if (isStreamingDeltaEvent(candidate)) {
+ mergeIndex = i;
+ break;
+ }
+ // Skip transparent metrics updates; stop at any genuine rendered event.
+ if (!isConversationStateUpdateEvent(candidate)) {
+ break;
+ }
+ }
+
+ if (mergeIndex !== -1) {
+ newUiEvents[mergeIndex] = mergeStreamingDeltaEvent(
+ event,
+ newUiEvents[mergeIndex] as StreamingDeltaEvent,
+ );
+ return newUiEvents;
+ }
+
+ newUiEvents.push(event);
+ return newUiEvents;
+ }
+
+ // The turn's final agent text supersedes the streaming deltas that produced
+ // it (when present), so reconcile before the generic handling below.
+ if (
+ (isActionEvent(event) && event.action.kind === "FinishAction") ||
+ (isMessageEvent(event) && event.llm_message.role === "assistant")
+ ) {
+ const finalizedUiEvents = finalizeStreamingDeltasInPlace(
+ event,
+ newUiEvents,
+ );
+ if (finalizedUiEvents) {
+ return finalizedUiEvents;
+ }
+ }
+
if (isACPToolCallEvent(event)) {
const existingIndex = newUiEvents.findIndex(
(uiEvent) =>
diff --git a/openhands/app_server/app_conversation/live_status_app_conversation_service.py b/openhands/app_server/app_conversation/live_status_app_conversation_service.py
index de4f59f79c..ffbc8ab41d 100644
--- a/openhands/app_server/app_conversation/live_status_app_conversation_service.py
+++ b/openhands/app_server/app_conversation/live_status_app_conversation_service.py
@@ -1245,6 +1245,8 @@ class LiveStatusAppConversationService(AppConversationServiceBase):
'base_url': base_url,
'api_key': user.agent_settings.llm.api_key,
'usage_id': 'agent',
+ # Force streaming on (the SDK LLM defaults stream=False).
+ 'stream': True,
}
)
diff --git a/openhands/app_server/settings/llm_profiles.py b/openhands/app_server/settings/llm_profiles.py
index 6ead5db089..4fedeac9b4 100644
--- a/openhands/app_server/settings/llm_profiles.py
+++ b/openhands/app_server/settings/llm_profiles.py
@@ -54,7 +54,9 @@ def resolve_profile_llm(
model=profile_llm.model,
base_url=profile_llm.base_url,
managed_proxy_url=managed_proxy_url,
- )
+ ),
+ # Force streaming on (profiles default to the SDK's stream=False).
+ 'stream': True,
}
)
if not has_real_api_key(resolved.api_key) and has_real_api_key(fallback_api_key):
diff --git a/tests/unit/app_server/test_app_conversation_router.py b/tests/unit/app_server/test_app_conversation_router.py
index 0f34843bbe..1ba2f9829e 100644
--- a/tests/unit/app_server/test_app_conversation_router.py
+++ b/tests/unit/app_server/test_app_conversation_router.py
@@ -659,6 +659,7 @@ class TestSwitchConversationProfile:
post_kwargs = client.post.await_args.kwargs
assert post_kwargs['json']['llm']['model'] == new_model
assert post_kwargs['json']['llm']['usage_id'].startswith('profile:gpt-5:')
+ assert post_kwargs['json']['llm']['stream'] is True
async def test_falls_back_to_settings_api_key_when_profile_has_none(self):
"""SaaS: managed profiles persist no key, so the switch must source the
diff --git a/tests/unit/app_server/test_live_status_app_conversation_service.py b/tests/unit/app_server/test_live_status_app_conversation_service.py
index cd55b843bd..a84d0dba4b 100644
--- a/tests/unit/app_server/test_live_status_app_conversation_service.py
+++ b/tests/unit/app_server/test_live_status_app_conversation_service.py
@@ -669,6 +669,7 @@ class TestLiveStatusAppConversationService:
assert llm.model == 'sdk-model'
assert llm.base_url == 'https://sdk-llm.example.com'
+ assert llm.stream is True
@pytest.mark.asyncio
async def test_configure_llm_preserves_reasoning_effort(self):