🙌 OpenHands: AI-Driven Development
V1 chat: group consecutive action/observation events (#165)
Robert Brennanadf407b78634
diff --git a/AGENTS.md b/AGENTS.mdindex f97461245a..33a8f03d03 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -123,6 +123,15 @@- Regression coverage for the CSS isolation work lives in `__tests__/agent-server-ui-providers.test.tsx`, `__tests__/agent-server-ui-style-scope.test.ts`, and the browser-level `tests/css-isolation.spec.ts` Playwright test.+- Action grouping in the chat stream:+ - `src/components/v1/chat/group-events.ts` folds runs of consecutive groupable events (regular `ActionEvent`/`ObservationEvent` cards, but not `FinishAction`, `ThinkAction`, `PlanningFileEditorObservation`, `TaskTrackerObservation`, hooks, errors, or message events) into single `RenderedItem` groups. The threshold lives in `EVENT_GROUP_MIN_SIZE` (currently 2, so even pairs of back-to-back actions get folded).+ - `EventGroup` (`src/components/v1/chat/event-message-components/event-group.tsx`) is the collapsible header that wraps each run. Default state is collapsed; the header shows `EVENT_GROUP$ACTIONS_COMPLETED` (with a success check) when the group is done, or `EVENT_GROUP$ACTIONS_PROGRESS` plus the currently-running action's title (from `getEventContent`) while a member `ActionEvent` has not yet been replaced by its observation in the UI events array. Expanding renders the original `EventMessage`s verbatim so each card still expands the way it did before.+ - Agent thoughts attached to an `ActionEvent` (`event.thought`) are hoisted out of groups: `groupEvents` emits a third `RenderedItem` kind `"thought"` whenever a groupable event carries (or, for an observation, originates from) a non-empty thought, flushing the current run and starting a new one. `messages.tsx` renders that item via `ThoughtEventMessage` and passes `suppressThought` to `EventMessage` so the inline thought isn't duplicated inside the group's expanded content. `ThinkAction` is excluded from this hoisting because the thought IS its action body and is rendered through its own codepath.+ - `groupEvents` now de-duplicates hoisted thoughts by action ID so mixed UI arrays that temporarily contain both an action and its replacement observation do not emit the same thought twice; `minSize` is treated as a validated internal invariant (`>= 1`).+ - `EventGroup` should return `null` for an empty `events` array and wire the toggle button to the expanded body with `aria-controls` / `role="region"` / `aria-labelledby`.+ - `src/components/v1/chat/messages.tsx` is the only consumer; the grouping is transparent to upstream code. Coverage lives in `__tests__/components/v1/chat/group-events.test.ts` (pure logic, including thought hoisting) and `__tests__/components/v1/chat/event-message-components/event-group.test.tsx` (rendering/interaction).++- Library packaging notes:- Public npm entrypoints now come from `src/index.ts` → `src/lib/index.ts`, with domain barrels under `src/components/{conversation,terminal,browser,files,settings,sidebar}/index.ts`.- `npm run build` remains the standalone app build (`react-router build`), while `npm run build:lib` runs `vite build` in library mode plus `tsc -p tsconfig.lib.json` to emit `.d.ts` files into `dist/`.diff --git a/__tests__/components/v1/chat/event-message-components/event-group.test.tsx b/__tests__/components/v1/chat/event-message-components/event-group.test.tsxnew file mode 100644index 0000000000..1313eb9898--- /dev/null+++ b/__tests__/components/v1/chat/event-message-components/event-group.test.tsx@@ -0,0 +1,181 @@+import { describe, it, expect } from "vitest";+import { screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { renderWithProviders } from "test-utils";+import { EventGroup } from "#/components/v1/chat/event-message-components/event-group";+import {+ ActionEvent,+ ObservationEvent,+ SecurityRisk,+} from "#/types/v1/core";+import { ExecuteBashAction } from "#/types/v1/core/base/action";+import { ExecuteBashObservation } from "#/types/v1/core/base/observation";++const makeBashAction = (+ id: string,+ command: string,+): ActionEvent<ExecuteBashAction> => ({+ id,+ timestamp: new Date().toISOString(),+ source: "agent",+ thought: [],+ thinking_blocks: [],+ action: {+ kind: "ExecuteBashAction",+ command,+ is_input: false,+ timeout: null,+ reset: false,+ },+ tool_name: "execute_bash",+ tool_call_id: `call_${id}`,+ tool_call: {+ id: `call_${id}`,+ type: "function",+ function: {+ name: "execute_bash",+ arguments: JSON.stringify({ command }),+ },+ },+ llm_response_id: `response_${id}`,+ security_risk: SecurityRisk.UNKNOWN,+});++const makeBashObservation = (+ id: string,+ actionId: string,+ command: string,+): ObservationEvent<ExecuteBashObservation> => ({+ id,+ timestamp: new Date().toISOString(),+ source: "environment",+ tool_name: "execute_bash",+ tool_call_id: `call_${actionId}`,+ action_id: actionId,+ observation: {+ kind: "ExecuteBashObservation",+ content: [{ type: "text", text: "ok" }],+ command,+ exit_code: 0,+ error: false,+ timeout: false,+ metadata: {} as never,+ },+});++describe("EventGroup", () => {+ it("returns null for an empty events array", () => {+ const { container } = renderWithProviders(+ <EventGroup events={[]}>+ <div>child</div>+ </EventGroup>,+ );++ expect(container).toBeEmptyDOMElement();+ });++ it("renders a 'completed' summary when all events are observations", () => {+ const events = [+ makeBashObservation("o1", "a1", "ls"),+ makeBashObservation("o2", "a2", "pwd"),+ makeBashObservation("o3", "a3", "whoami"),+ ];++ renderWithProviders(+ <EventGroup events={events}>+ <div data-testid="child">child content</div>+ </EventGroup>,+ );++ expect(+ screen.getByText("EVENT_GROUP$ACTIONS_COMPLETED"),+ ).toBeInTheDocument();+ // Children should not be visible in the collapsed state.+ expect(screen.queryByTestId("child")).not.toBeInTheDocument();+ });++ it("renders a progress summary and the running action title while in flight", () => {+ const events = [+ makeBashObservation("o1", "a1", "ls"),+ makeBashObservation("o2", "a2", "pwd"),+ // Last action has NOT been replaced by an observation -> still running.+ makeBashAction("a3", "echo hello"),+ ];++ renderWithProviders(+ <EventGroup events={events}>+ <div>child</div>+ </EventGroup>,+ );++ expect(+ screen.getByText("EVENT_GROUP$ACTIONS_PROGRESS"),+ ).toBeInTheDocument();+ // The running action's title is rendered next to the summary. Translations+ // aren't loaded in tests, so we just verify the action's translation key+ // shows up (the localized version would interpolate the command).+ expect(screen.getByText(/ACTION_MESSAGE\$RUN/)).toBeInTheDocument();+ });++ it("hides the success indicator while running and shows it when done", () => {+ const running = [+ makeBashObservation("o1", "a1", "ls"),+ makeBashAction("a2", "pwd"),+ ];++ const { rerender } = renderWithProviders(+ <EventGroup events={running}>+ <div>child</div>+ </EventGroup>,+ );+ expect(screen.queryByTestId("status-icon")).not.toBeInTheDocument();++ const done = [+ makeBashObservation("o1", "a1", "ls"),+ makeBashObservation("o2", "a2", "pwd"),+ ];+ rerender(+ <EventGroup events={done}>+ <div>child</div>+ </EventGroup>,+ );+ expect(screen.getByTestId("status-icon")).toBeInTheDocument();+ });++ it("updates accessibility state while toggling the group", async () => {+ const events = [+ makeBashObservation("o1", "a1", "ls"),+ makeBashObservation("o2", "a2", "pwd"),+ makeBashObservation("o3", "a3", "whoami"),+ ];+ const user = userEvent.setup();++ renderWithProviders(+ <EventGroup events={events}>+ <div data-testid="child">child content</div>+ </EventGroup>,+ );++ const toggle = screen.getByTestId("event-group-toggle");+ expect(toggle).toHaveAttribute("aria-expanded", "false");+ expect(toggle).toHaveAttribute("aria-label", "EVENT_GROUP$EXPAND");+ expect(screen.queryByRole("region")).not.toBeInTheDocument();+ expect(screen.queryByTestId("child")).not.toBeInTheDocument();++ await user.click(toggle);++ const content = screen.getByRole("region");+ expect(toggle).toHaveAttribute("aria-expanded", "true");+ expect(toggle).toHaveAttribute("aria-label", "EVENT_GROUP$COLLAPSE");+ expect(toggle).toHaveAttribute("aria-controls", content.id);+ expect(content).toHaveAttribute("aria-labelledby", toggle.id);+ expect(screen.getByTestId("child")).toBeInTheDocument();++ await user.click(toggle);++ expect(toggle).toHaveAttribute("aria-expanded", "false");+ expect(toggle).toHaveAttribute("aria-label", "EVENT_GROUP$EXPAND");+ expect(screen.queryByRole("region")).not.toBeInTheDocument();+ expect(screen.queryByTestId("child")).not.toBeInTheDocument();+ });+});diff --git a/__tests__/components/v1/chat/group-events.test.ts b/__tests__/components/v1/chat/group-events.test.tsnew file mode 100644index 0000000000..351d6c1d9c--- /dev/null+++ b/__tests__/components/v1/chat/group-events.test.ts@@ -0,0 +1,415 @@+import { describe, it, expect } from "vitest";+import {+ groupEvents,+ isGroupableEvent,+ EVENT_GROUP_MIN_SIZE,+} from "#/components/v1/chat/group-events";+import {+ ActionEvent,+ AgentErrorEvent,+ HookExecutionEvent,+ MessageEvent,+ ObservationEvent,+ SecurityRisk,+} from "#/types/v1/core";+import { TextContent } from "#/types/v1/core/base/common";+import {+ ExecuteBashAction,+ FinishAction,+ ThinkAction,+} from "#/types/v1/core/base/action";+import {+ ExecuteBashObservation,+ PlanningFileEditorObservation,+ TaskTrackerObservation,+} from "#/types/v1/core/base/observation";++const makeBashAction = (+ id: string,+ thought: TextContent[] = [],+): ActionEvent<ExecuteBashAction> => ({+ id,+ timestamp: new Date().toISOString(),+ source: "agent",+ thought,+ thinking_blocks: [],+ action: {+ kind: "ExecuteBashAction",+ command: `echo ${id}`,+ is_input: false,+ timeout: null,+ reset: false,+ },+ tool_name: "execute_bash",+ tool_call_id: `call_${id}`,+ tool_call: {+ id: `call_${id}`,+ type: "function",+ function: {+ name: "execute_bash",+ arguments: JSON.stringify({ command: `echo ${id}` }),+ },+ },+ llm_response_id: `response_${id}`,+ security_risk: SecurityRisk.UNKNOWN,+});++const makeBashObservation = (+ id: string,+ actionId: string,+): ObservationEvent<ExecuteBashObservation> => ({+ id,+ timestamp: new Date().toISOString(),+ source: "environment",+ tool_name: "execute_bash",+ tool_call_id: `call_${actionId}`,+ action_id: actionId,+ observation: {+ kind: "ExecuteBashObservation",+ content: [{ type: "text", text: "ok" }],+ command: `echo ${actionId}`,+ exit_code: 0,+ error: false,+ timeout: false,+ metadata: {} as never,+ },+});++const makeUserMessage = (id: string): MessageEvent => ({+ id,+ timestamp: new Date().toISOString(),+ source: "user",+ llm_message: {+ role: "user",+ content: [{ type: "text", text: "hi" }],+ },+ activated_microagents: [],+ extended_content: [],+});++const makeFinishAction = (id: string): ActionEvent<FinishAction> => ({+ ...makeBashAction(id),+ action: { kind: "FinishAction", message: "all done" },+});++const makeThinkAction = (id: string): ActionEvent<ThinkAction> => ({+ ...makeBashAction(id),+ action: { kind: "ThinkAction", thought: "thinking" },+});++const makePlanObs = (+ id: string,+ actionId: string,+): ObservationEvent<PlanningFileEditorObservation> => ({+ ...makeBashObservation(id, actionId),+ observation: {+ kind: "PlanningFileEditorObservation",+ content: [{ type: "text", text: "plan" }],+ } as PlanningFileEditorObservation,+});++const makeTaskTrackerObservation = (+ id: string,+ actionId: string,+): ObservationEvent<TaskTrackerObservation> => ({+ ...makeBashObservation(id, actionId),+ observation: {+ kind: "TaskTrackerObservation",+ content: "task list",+ command: "plan",+ task_list: [{ title: "Task", notes: "Notes", status: "todo" }],+ },+});++const makeAgentErrorEvent = (id: string): AgentErrorEvent => ({+ id,+ timestamp: new Date().toISOString(),+ source: "agent",+ tool_name: "execute_bash",+ tool_call_id: `call_${id}`,+ error: "boom",+});++const makeHookExecutionEvent = (id: string): HookExecutionEvent => ({+ id,+ timestamp: new Date().toISOString(),+ kind: "HookExecutionEvent",+ source: "hook",+ hook_event_type: "PreToolUse",+ hook_command: "echo hook",+ success: true,+ blocked: false,+ exit_code: 0,+ reason: null,+ tool_name: "execute_bash",+ action_id: "a1",+ message_id: null,+ stdout: "",+ stderr: "",+ error: null,+ additional_context: null,+ hook_input: null,+});++describe("isGroupableEvent", () => {+ it("groups regular action events", () => {+ expect(isGroupableEvent(makeBashAction("a1"))).toBe(true);+ });++ it("groups regular observation events", () => {+ expect(isGroupableEvent(makeBashObservation("o1", "a1"))).toBe(true);+ });++ it("does not group user messages", () => {+ expect(isGroupableEvent(makeUserMessage("m1"))).toBe(false);+ });++ it("does not group FinishAction", () => {+ expect(isGroupableEvent(makeFinishAction("a1"))).toBe(false);+ });++ it("does not group ThinkAction", () => {+ expect(isGroupableEvent(makeThinkAction("a1"))).toBe(false);+ });++ it("does not group PlanningFileEditorObservation", () => {+ expect(isGroupableEvent(makePlanObs("o1", "a1"))).toBe(false);+ });++ it("does not group TaskTrackerObservation", () => {+ expect(isGroupableEvent(makeTaskTrackerObservation("o1", "a1"))).toBe(false);+ });++ it("does not group AgentErrorEvent", () => {+ expect(isGroupableEvent(makeAgentErrorEvent("e1"))).toBe(false);+ });++ it("does not group HookExecutionEvent", () => {+ expect(isGroupableEvent(makeHookExecutionEvent("h1"))).toBe(false);+ });+});++describe("groupEvents", () => {+ it("returns an empty list for no events", () => {+ expect(groupEvents([])).toEqual([]);+ });++ it("requires minSize to be at least 1", () => {+ expect(() => groupEvents([], 0)).toThrow("minSize must be at least 1");+ });++ it("emits singles when there are not enough actions in a row", () => {+ const events = [+ makeUserMessage("m1"),+ makeBashObservation("o1", "a1"),+ makeUserMessage("m2"),+ ];++ // 1 < EVENT_GROUP_MIN_SIZE (2), so the lone observation stays a single.+ const result = groupEvents(events);+ expect(result.every((item) => item.kind === "single")).toBe(true);+ expect(result).toHaveLength(3);+ });++ it("groups even a pair of consecutive actions", () => {+ const events = [+ makeUserMessage("m1"),+ makeBashObservation("o1", "a1"),+ makeBashObservation("o2", "a2"),+ makeUserMessage("m2"),+ ];++ // 2 == EVENT_GROUP_MIN_SIZE (2), so the pair folds into a group.+ const result = groupEvents(events);+ expect(result).toHaveLength(3);+ expect(result[0]).toMatchObject({ kind: "single", index: 0 });+ expect(result[1]).toMatchObject({ kind: "group", startIndex: 1 });+ if (result[1].kind === "group") {+ expect(result[1].events).toHaveLength(2);+ }+ expect(result[2]).toMatchObject({ kind: "single", index: 3 });+ });++ it("groups runs of >= EVENT_GROUP_MIN_SIZE events", () => {+ const events = [+ makeUserMessage("m1"),+ makeBashObservation("o1", "a1"),+ makeBashObservation("o2", "a2"),+ makeBashObservation("o3", "a3"),+ makeBashObservation("o4", "a4"),+ makeUserMessage("m2"),+ ];++ const result = groupEvents(events);+ // user, group(4), user+ expect(result).toHaveLength(3);+ expect(result[0]).toMatchObject({ kind: "single", index: 0 });+ expect(result[1]).toMatchObject({ kind: "group", startIndex: 1 });+ if (result[1].kind === "group") {+ expect(result[1].events).toHaveLength(4);+ }+ expect(result[2]).toMatchObject({ kind: "single", index: 5 });+ });++ it("includes a still-pending action in the group", () => {+ // Last action hasn't been replaced by an observation yet -> the group+ // should still include it so the header can show a running indicator.+ const events = [+ makeBashObservation("o1", "a1"),+ makeBashObservation("o2", "a2"),+ makeBashAction("a3"),+ ];++ const result = groupEvents(events);+ expect(result).toHaveLength(1);+ expect(result[0].kind).toBe("group");+ if (result[0].kind === "group") {+ expect(result[0].events).toHaveLength(3);+ }+ });++ it("breaks the group when a non-groupable event interrupts", () => {+ const events = [+ makeBashObservation("o1", "a1"),+ makeBashObservation("o2", "a2"),+ makeBashObservation("o3", "a3"),+ makeUserMessage("m1"),+ makeBashObservation("o4", "a4"),+ makeBashObservation("o5", "a5"),+ makeBashObservation("o6", "a6"),+ ];++ const result = groupEvents(events);+ expect(result).toHaveLength(3);+ expect(result[0].kind).toBe("group");+ expect(result[1].kind).toBe("single");+ expect(result[2].kind).toBe("group");+ });++ it("respects a custom minSize", () => {+ const events = [+ makeBashObservation("o1", "a1"),+ makeBashObservation("o2", "a2"),+ ];++ const grouped = groupEvents(events, 2);+ expect(grouped).toHaveLength(1);+ expect(grouped[0].kind).toBe("group");+ });++ it("hoists an action's thought into a separate item and starts a new group", () => {+ // First three actions have no thought, then a fourth action carries a+ // thought, then two more actions follow. The thought should break the+ // first group and open a new one starting with the thought-bearing+ // action.+ const a1 = makeBashAction("a1");+ const a2 = makeBashAction("a2");+ const a3 = makeBashAction("a3");+ const a4 = makeBashAction("a4", [+ { type: "text", text: "Let me check tests for the new conversation button:" },+ ]);+ const a5 = makeBashAction("a5");+ const a6 = makeBashAction("a6");++ const events = [+ makeBashObservation("o1", "a1"),+ makeBashObservation("o2", "a2"),+ makeBashObservation("o3", "a3"),+ makeBashObservation("o4", "a4"),+ makeBashObservation("o5", "a5"),+ makeBashObservation("o6", "a6"),+ ];+ const allEvents = [a1, a2, a3, ...events.slice(0, 3), a4, a5, a6, ...events.slice(3)];++ const result = groupEvents(events, undefined, allEvents);++ // group(o1..o3), thought(a4), group(o4..o6)+ expect(result).toHaveLength(3);+ expect(result[0].kind).toBe("group");+ expect(result[1].kind).toBe("thought");+ expect(result[2].kind).toBe("group");++ if (result[0].kind === "group") {+ expect(result[0].events).toHaveLength(3);+ }+ if (result[1].kind === "thought") {+ expect(result[1].action.id).toBe("a4");+ }+ if (result[2].kind === "group") {+ expect(result[2].events).toHaveLength(3);+ }+ });++ it("hoists thoughts attached to action events that haven't been observed yet", () => {+ const events = [+ makeBashAction("a1"),+ makeBashAction("a2"),+ makeBashAction("a3", [{ type: "text", text: "thinking out loud" }]),+ ];++ const result = groupEvents(events);++ // a1 + a2 group together (>= min size of 2), then the thought is hoisted+ // out before a3, leaving a3 as a single.+ expect(result.map((item) => item.kind)).toEqual([+ "group",+ "thought",+ "single",+ ]);+ });++ it("does not emit the same thought twice when both action and observation are present", () => {+ const action = makeBashAction("a1", [+ { type: "text", text: "thinking out loud" },+ ]);+ const observation = makeBashObservation("o1", "a1");++ const result = groupEvents(+ [action, observation],+ undefined,+ [action, observation],+ );++ expect(result.map((item) => item.kind)).toEqual(["thought", "group"]);+ if (result[1].kind === "group") {+ expect(result[1].events).toEqual([action, observation]);+ }+ });++ it("ignores empty thoughts", () => {+ const events = [+ makeBashAction("a1", [{ type: "text", text: " " }]),+ makeBashAction("a2"),+ makeBashAction("a3"),+ ];++ const result = groupEvents(events);++ // Whitespace-only thought should not break the group.+ expect(result).toHaveLength(1);+ expect(result[0].kind).toBe("group");+ });++ it("does not hoist a ThinkAction's thought (it has its own rendering)", () => {+ const events = [+ makeBashAction("a1"),+ makeBashAction("a2"),+ makeBashAction("a3"),+ makeThinkAction("t1"),+ makeBashAction("a4"),+ makeBashAction("a5"),+ makeBashAction("a6"),+ ];++ const result = groupEvents(events);++ // ThinkAction breaks the run as a single (it isn't groupable), but no+ // additional "thought" item should be emitted for it because the+ // ThinkAction's body already renders the thought.+ expect(result.map((item) => item.kind)).toEqual([+ "group",+ "single",+ "group",+ ]);+ });+});diff --git a/src/components/features/chat/generic-event-message.tsx b/src/components/features/chat/generic-event-message.tsxindex e82d11e927..ccb29bdb2a 100644--- a/src/components/features/chat/generic-event-message.tsx+++ b/src/components/features/chat/generic-event-message.tsx@@ -4,6 +4,7 @@ import ArrowUp from "#/icons/angle-up-solid.svg?react";import { SuccessIndicator } from "./success-indicator";import { ObservationResultStatus } from "./event-content-helpers/get-observation-result";import { MarkdownRenderer } from "../markdown/markdown-renderer";+import { IsInEventGroupContext } from "./is-in-event-group-context";interface GenericEventMessageProps {title: React.ReactNode;@@ -25,6 +26,7 @@ export function GenericEventMessage({titleTrailing,}: GenericEventMessageProps) {const [showDetails, setShowDetails] = React.useState(initiallyExpanded);+ const isInEventGroup = React.useContext(IsInEventGroupContext);const chevron = details ? (<button@@ -50,7 +52,13 @@ export function GenericEventMessage({) : null;return (- <div className="flex flex-col gap-2 border-l-2 pl-2 my-2 py-2 border-neutral-300 text-sm w-full">+ <div+ className={+ isInEventGroup+ ? "flex flex-col gap-2 my-2 py-2 text-sm w-full"+ : "flex flex-col gap-2 border-l-2 pl-2 my-2 py-2 border-neutral-300 text-sm w-full"+ }+ ><div className="flex items-center justify-between font-bold text-neutral-300"><div className="flex items-center">{chevronPosition === "before" && chevron}diff --git a/src/components/features/chat/is-in-event-group-context.ts b/src/components/features/chat/is-in-event-group-context.tsnew file mode 100644index 0000000000..a737906cc6--- /dev/null+++ b/src/components/features/chat/is-in-event-group-context.ts@@ -0,0 +1,9 @@+import { createContext } from "react";++/**+ * True when the consuming event message is rendered inside an `EventGroup`'s+ * expanded children. Components like `GenericEventMessage` use this to drop+ * their own left bar so we don't render a redundant inner bar on top of the+ * group's outer bar.+ */+export const IsInEventGroupContext = createContext(false);diff --git a/src/components/v1/chat/event-message-components/event-group.tsx b/src/components/v1/chat/event-message-components/event-group.tsxnew file mode 100644index 0000000000..4e42b32058--- /dev/null+++ b/src/components/v1/chat/event-message-components/event-group.tsx@@ -0,0 +1,110 @@+import React from "react";+import { useTranslation } from "react-i18next";+import ArrowDown from "#/icons/angle-down-solid.svg?react";+import ArrowUp from "#/icons/angle-up-solid.svg?react";+import { OpenHandsEvent, ActionEvent } from "#/types/v1/core";+import { isActionEvent, isObservationEvent } from "#/types/v1/type-guards";+import { I18nKey } from "#/i18n/declaration";+import { SuccessIndicator } from "../../../features/chat/success-indicator";+import { getEventContent } from "../event-content-helpers/get-event-content";+import { IsInEventGroupContext } from "../../../features/chat/is-in-event-group-context";++interface EventGroupProps {+ /** The events represented by this group. Used to compute the summary. */+ events: OpenHandsEvent[];+ /** The fully-rendered event messages to show when the group is expanded. */+ children: React.ReactNode;+}++/**+ * Collapsible container that wraps a run of consecutive agent action/observation+ * events into a single summary card.+ *+ * Collapsed:+ * - While running: "{completed} of {total} actions" + the title of the+ * currently-running action.+ * - When done: "{count} actions completed" with a success check.+ *+ * Expanded:+ * - Renders the children verbatim, so each individual action/observation can+ * still be expanded the way it was before grouping.+ */+export function EventGroup({ events, children }: EventGroupProps) {+ const { t } = useTranslation("openhands");+ const [expanded, setExpanded] = React.useState(false);+ const contentId = React.useId();+ const buttonId = `${contentId}-toggle`;++ if (events.length === 0) {+ return null;+ }++ // Each ObservationEvent in the group is a completed action.+ // An ActionEvent that's still here (i.e. not yet replaced by its observation+ // in the UI events array) is the action currently in flight.+ const pendingAction = events.find((e): e is ActionEvent => isActionEvent(e));+ const completedCount = events.filter(isObservationEvent).length;+ const totalCount = events.length;+ const isRunning = !!pendingAction;++ const runningTitle = pendingAction+ ? getEventContent(pendingAction).title+ : null;++ const summary = isRunning+ ? t(I18nKey.EVENT_GROUP$ACTIONS_PROGRESS, {+ completed: completedCount,+ total: totalCount,+ })+ : t(I18nKey.EVENT_GROUP$ACTIONS_COMPLETED, { count: totalCount });++ const Chevron = expanded ? ArrowUp : ArrowDown;++ return (+ <div+ className="my-2 w-full border-l-2 border-neutral-300 pl-2 py-2 text-sm"+ data-testid="event-group"+ >+ <button+ id={buttonId}+ type="button"+ onClick={() => setExpanded((prev) => !prev)}+ aria-controls={contentId}+ aria-expanded={expanded}+ aria-label={+ expanded+ ? t(I18nKey.EVENT_GROUP$COLLAPSE)+ : t(I18nKey.EVENT_GROUP$EXPAND)+ }+ data-testid="event-group-toggle"+ className="w-full flex items-center justify-between gap-2 text-left cursor-pointer font-bold text-neutral-300"+ >+ <span className="flex items-center gap-2 min-w-0">+ <Chevron className="h-4 w-4 fill-neutral-300 flex-shrink-0" />+ <span className="truncate">{summary}</span>+ {isRunning && runningTitle && (+ <span className="font-normal text-neutral-400 truncate">+ <span className="mx-1">·</span>+ {runningTitle}+ </span>+ )}+ </span>+ {!isRunning && <SuccessIndicator status="success" />}+ </button>++ {expanded && (+ <div+ id={contentId}+ role="region"+ aria-labelledby={buttonId}+ className="mt-2 flex flex-col"+ data-testid="event-group-content"+ >+ <IsInEventGroupContext.Provider value>+ {children}+ </IsInEventGroupContext.Provider>+ </div>+ )}+ </div>+ );+}diff --git a/src/components/v1/chat/event-message-components/index.ts b/src/components/v1/chat/event-message-components/index.tsindex 52df9ab096..1acf8c9371 100644--- a/src/components/v1/chat/event-message-components/index.ts+++ b/src/components/v1/chat/event-message-components/index.ts@@ -5,3 +5,4 @@ export { FinishEventMessage } from "./finish-event-message";export { GenericEventMessageWrapper } from "./generic-event-message-wrapper";export { ThoughtEventMessage } from "./thought-event-message";export { HookExecutionEventMessage } from "./hook-execution-event-message";+export { EventGroup } from "./event-group";diff --git a/src/components/v1/chat/event-message.tsx b/src/components/v1/chat/event-message.tsxindex 1dfb6c26bf..146a4d1145 100644--- a/src/components/v1/chat/event-message.tsx+++ b/src/components/v1/chat/event-message.tsx@@ -34,6 +34,14 @@ interface EventMessageProps {isInLast10Actions: boolean;/** Set of event IDs that should render PlanPreview (one per user message phase) */planPreviewEventIds?: Set<string>;+ /**+ * When true, do not render the inline `ThoughtEventMessage` for action /+ * observation events. The caller is expected to render the thought+ * separately (e.g. via a hoisted "thought" rendered item) so the message+ * pane and the in-group rendering don't double up on the same content.+ * Has no effect on `ThinkAction`, whose thought IS its action body.+ */+ suppressThought?: boolean;}/**@@ -122,6 +130,7 @@ export function EventMessage({isLastMessage,isInLast10Actions,planPreviewEventIds,+ suppressThought = false,}: EventMessageProps) {const { data: config } = useConfig();const { planContent } = useConversationStore();@@ -190,10 +199,12 @@ export function EventMessage({if (isActionEvent(event)) {return (<>- <ThoughtEventMessage- event={event}- isFromPlanningAgent={isFromPlanningAgent}- />+ {!suppressThought && (+ <ThoughtEventMessage+ event={event}+ isFromPlanningAgent={isFromPlanningAgent}+ />+ )}<GenericEventMessageWrapperevent={event}isLastMessage={isLastMessage}@@ -235,6 +246,7 @@ export function EventMessage({// Skip ThoughtEventMessage for ThinkAction (thought IS the action)const shouldShowThought =+ !suppressThought &&correspondingAction &&isActionEvent(correspondingAction) &&correspondingAction.action.kind !== "ThinkAction";diff --git a/src/components/v1/chat/event-thought-helpers.ts b/src/components/v1/chat/event-thought-helpers.tsnew file mode 100644index 0000000000..afdb03b6cf--- /dev/null+++ b/src/components/v1/chat/event-thought-helpers.ts@@ -0,0 +1,47 @@+import { ActionEvent, OpenHandsEvent } from "#/types/v1/core";+import { isActionEvent, isObservationEvent } from "#/types/v1/type-guards";++/**+ * Returns the displayable thought text of an `ActionEvent`, or an empty+ * string if the event has no usable thought content.+ *+ * Mirrors the logic used by `ThoughtEventMessage` so callers stay in sync+ * with what gets rendered.+ */+export const getActionThoughtText = (action: ActionEvent): string =>+ action.thought+ .filter((t) => t.type === "text")+ .map((t) => t.text)+ .join("\n");++export const hasNonEmptyThought = (action: ActionEvent): boolean =>+ getActionThoughtText(action).trim().length > 0;++/**+ * Find the `ActionEvent` whose thought should be rendered alongside the+ * given UI event. For an `ActionEvent` the thought belongs to itself; for+ * an `ObservationEvent` we look up the matching action in `allEvents`.+ *+ * `ThinkAction` is intentionally excluded because its thought IS the+ * action body and is rendered through a separate codepath.+ */+export const getThoughtSourceAction = (+ event: OpenHandsEvent,+ allEvents: OpenHandsEvent[],+): ActionEvent | null => {+ if (isActionEvent(event)) {+ if (event.action.kind === "ThinkAction") return null;+ return hasNonEmptyThought(event) ? event : null;+ }++ if (isObservationEvent(event)) {+ const action = allEvents.find(+ (e): e is ActionEvent => isActionEvent(e) && e.id === event.action_id,+ );+ if (!action) return null;+ if (action.action.kind === "ThinkAction") return null;+ return hasNonEmptyThought(action) ? action : null;+ }++ return null;+};diff --git a/src/components/v1/chat/group-events.ts b/src/components/v1/chat/group-events.tsnew file mode 100644index 0000000000..842166244b--- /dev/null+++ b/src/components/v1/chat/group-events.ts@@ -0,0 +1,112 @@+import { ActionEvent, OpenHandsEvent } from "#/types/v1/core";+import {+ isActionEvent,+ isObservationEvent,+ isPlanningFileEditorObservationEvent,+} from "#/types/v1/type-guards";+import { getThoughtSourceAction } from "./event-thought-helpers";++/** Minimum run-length before consecutive actions get folded into a single+ * collapsible group. Even pairs are folded so the chat scroll stays compact+ * when the agent fires off back-to-back tool calls. */+export const EVENT_GROUP_MIN_SIZE = 2;++/**+ * Returns true if the given event is one of the action / observation cards+ * that we want to fold into an `EventGroup` when several appear in a row.+ *+ * Events that have their own dedicated rendering (FinishAction, ThinkAction,+ * HookExecution, AgentError, MessageEvent, PlanPreview, TaskTracker) are+ * treated as group breakers.+ */+export const isGroupableEvent = (event: OpenHandsEvent): boolean => {+ if (isActionEvent(event)) {+ const { kind } = event.action;+ if (kind === "FinishAction" || kind === "ThinkAction") {+ return false;+ }+ return true;+ }++ if (isObservationEvent(event)) {+ if (isPlanningFileEditorObservationEvent(event)) {+ return false;+ }+ if (event.observation.kind === "TaskTrackerObservation") {+ return false;+ }+ return true;+ }++ return false;+};++export type RenderedItem =+ | { kind: "single"; event: OpenHandsEvent; index: number }+ | { kind: "thought"; action: ActionEvent; index: number }+ | { kind: "group"; events: OpenHandsEvent[]; startIndex: number };++/**+ * Walk a list of UI events and bucket consecutive groupable events into+ * `group` items. Anything that breaks the run, or runs shorter than+ * `EVENT_GROUP_MIN_SIZE`, is emitted as `single` items so they keep rendering+ * the way they always have.+ *+ * Whenever a groupable event carries an agent thought (either an+ * `ActionEvent.thought` or the corresponding action of an+ * `ObservationEvent`), the thought is hoisted out as its own `thought`+ * `RenderedItem`, the current run is flushed, and a new run is started with+ * the event itself. This keeps reasoning text in the main message stream+ * instead of buried inside a collapsed action group.+ *+ * `allEvents` should be the full event history so observations can find+ * their matching action; if omitted, it defaults to `events`.+ */+export const groupEvents = (+ events: OpenHandsEvent[],+ minSize: number = EVENT_GROUP_MIN_SIZE,+ allEvents: OpenHandsEvent[] = events,+): RenderedItem[] => {+ if (minSize < 1) {+ throw new Error("minSize must be at least 1");+ }++ const items: RenderedItem[] = [];+ const emittedThoughtActionIds = new Set<string>();+ let run: { events: OpenHandsEvent[]; startIndex: number } | null = null;++ const flushRun = () => {+ if (!run) return;+ if (run.events.length >= minSize) {+ items.push({+ kind: "group",+ events: run.events,+ startIndex: run.startIndex,+ });+ } else {+ run.events.forEach((event, offset) => {+ items.push({ kind: "single", event, index: run!.startIndex + offset });+ });+ }+ run = null;+ };++ events.forEach((event, index) => {+ if (isGroupableEvent(event)) {+ const thoughtAction = getThoughtSourceAction(event, allEvents);+ if (thoughtAction && !emittedThoughtActionIds.has(thoughtAction.id)) {+ flushRun();+ emittedThoughtActionIds.add(thoughtAction.id);+ items.push({ kind: "thought", action: thoughtAction, index });+ }+ if (!run) run = { events: [], startIndex: index };+ run.events.push(event);+ } else {+ flushRun();+ items.push({ kind: "single", event, index });+ }+ });++ flushRun();+ return items;+};diff --git a/src/components/v1/chat/messages.tsx b/src/components/v1/chat/messages.tsxindex b0a4450282..4d05d828ab 100644--- a/src/components/v1/chat/messages.tsx+++ b/src/components/v1/chat/messages.tsx@@ -4,6 +4,8 @@ import { EventMessage } from "./event-message";import { ChatMessage } from "../../features/chat/chat-message";import { useOptimisticUserMessageStore } from "#/stores/optimistic-user-message-store";import { usePlanPreviewEvents } from "./hooks/use-plan-preview-events";+import { groupEvents } from "./group-events";+import { EventGroup, ThoughtEventMessage } from "./event-message-components";// TODO: Implement microagent functionality for V1 when APIs support V1 event IDs// import { AgentState } from "#/types/agent-state";// import MemoryIcon from "#/icons/memory_icon.svg?react";@@ -13,6 +15,8 @@ interface MessagesProps {allEvents: OpenHandsEvent[]; // Full event history (for action lookup)}+const getLastEventId = (events: OpenHandsEvent[]) => events.at(-1)?.id;+export const Messages: React.FC<MessagesProps> = React.memo(({ messages, allEvents }) => {const { getOptimisticUserMessage } = useOptimisticUserMessageStore();@@ -23,26 +27,60 @@ export const Messages: React.FC<MessagesProps> = React.memo(// This ensures only one preview per user message "phase"const planPreviewEventIds = usePlanPreviewEvents(allEvents);- // TODO: Implement microagent functionality for V1 if needed- // For now, we'll skip microagent features+ // Fold consecutive action/observation events into collapsible groups so a+ // long sequence of tool calls doesn't dominate the chat scroll. Items that+ // can't be grouped (or that fall in a short run) are still rendered one by+ // one, identically to before. Agent thoughts attached to an action are+ // hoisted out as their own rendered item so they always show up in the+ // message pane and a thought between actions starts a fresh group.+ const renderedItems = React.useMemo(+ () => groupEvents(messages, undefined, allEvents),+ [messages, allEvents],+ );++ const renderEventMessage = (+ event: OpenHandsEvent,+ index: number,+ suppressThought: boolean,+ ) => (+ <EventMessage+ key={event.id}+ event={event}+ messages={allEvents}+ isLastMessage={messages.length - 1 === index}+ isInLast10Actions={messages.length - 1 - index < 10}+ planPreviewEventIds={planPreviewEventIds}+ suppressThought={suppressThought}+ />+ );return (<>- {messages.map((message, index) => (- <EventMessage- key={message.id}- event={message}- messages={allEvents}- isLastMessage={messages.length - 1 === index}- isInLast10Actions={messages.length - 1 - index < 10}- planPreviewEventIds={planPreviewEventIds}- // Microagent props - not implemented yet for V1- // microagentStatus={undefined}- // microagentConversationId={undefined}- // microagentPRUrl={undefined}- // actions={undefined}- />- ))}+ {renderedItems.map((item) => {+ if (item.kind === "single") {+ // Thoughts for singles are also hoisted as their own "thought"+ // item, so suppress the inline render to avoid duplication.+ return renderEventMessage(item.event, item.index, true);+ }++ if (item.kind === "thought") {+ return (+ <ThoughtEventMessage+ key={`thought-${item.action.id}`}+ event={item.action}+ />+ );+ }++ const groupKey = item.events[0]?.id ?? `group-${item.startIndex}`;+ return (+ <EventGroup key={groupKey} events={item.events}>+ {item.events.map((event, offset) =>+ renderEventMessage(event, item.startIndex + offset, true),+ )}+ </EventGroup>+ );+ })}{optimisticUserMessage && (<ChatMessage type="user" message={optimisticUserMessage} />@@ -50,14 +88,11 @@ 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;- },+ (prevProps, nextProps) =>+ prevProps.messages.length === nextProps.messages.length &&+ prevProps.allEvents.length === nextProps.allEvents.length &&+ getLastEventId(prevProps.messages) === getLastEventId(nextProps.messages) &&+ getLastEventId(prevProps.allEvents) === getLastEventId(nextProps.allEvents),);Messages.displayName = "Messages";diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 9d1c35b67d..f38d993208 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -22591,5 +22591,17 @@"ca": "Confirma les preferències","tr": "Tercihleri onayla","uk": "Підтвердити налаштування"+ },+ "EVENT_GROUP$ACTIONS_COMPLETED": {+ "en": "{{count}} actions completed"+ },+ "EVENT_GROUP$ACTIONS_PROGRESS": {+ "en": "{{completed}} of {{total}} actions"+ },+ "EVENT_GROUP$EXPAND": {+ "en": "Expand actions"+ },+ "EVENT_GROUP$COLLAPSE": {+ "en": "Collapse actions"}}