Skip to content

🙌 OpenHands: AI-Driven Development

feat: collapse thinking and extended reasoning into collapsible sections (#409)

Xingyao Wang3a0eb9a9b172
diff --git a/AGENTS.md b/AGENTS.md
index 963f07f0ca..85e6d8c721 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -33,6 +33,8 @@
- Target specific elements via `page.getByTestId()` rather than full-page screenshots when possible.
- **Composing tests**: Use `test.step()` for iterative snapshots within a single test, or extract helper functions (like `navigateToSettings(page)`) to share setup across tests. For heavier reuse, use Playwright fixtures via `test.extend()`.
- Snapshots are organized by `{snapshotDir}/{testFilePath}/{projectName}/{arg}.png` (configured in `playwright.config.ts`).
+- **Conversation page snapshot tests**: The dev server uses MSW service workers for API mocking. For conversation-page tests, rely on MSW's pre-defined mock conversations (IDs "1", "2", "3" in `src/mocks/conversation-handlers.ts`) rather than fighting Playwright route interception. MSW's service worker intercepts requests before Playwright `page.route()` can; Playwright route interceptors only see requests that escape the service worker. Stub WebSocket via `page.addInitScript()` and inject events into the Zustand store via the exposed `window.__OH_EVENT_STORE__` API. Use `test.describe.configure({ mode: "serial" })` for conversation tests since the WebSocket stub + heavier page setup can cause intermittent failures in parallel mode.
+- **Baseline generation for CI**: Baselines generated locally will NOT match CI (different OS, fonts, rendering). Always regenerate baselines in CI after adding new snapshot tests: trigger the "Snapshot Tests" workflow manually with `update_snapshots=true`. The workflow commits updated baselines with `[skip ci]`, so push an empty commit afterward to trigger a fresh CI run that validates against the new baselines.
## Live End-to-End Test Framework
@@ -249,5 +251,7 @@
- Files tab diff-view default logic: keyed off `useHasAttachedSource()` (`src/hooks/use-has-attached-source.ts`), which is true when the user explicitly attached *either* a repo (`conversation.selected_repository`) *or* a local workspace (`getStoredConversationMetadata(id).selected_workspace`, persisted by `createConversation` when `workingDirOverride` is supplied). The agent-server pre-initialises every conversation workspace as a git worktree for its own change tracking, so do NOT use a filesystem probe (`git status` / `useUnifiedGetGitChanges`) as the attachment signal — that was tried in earlier iterations and made every fresh no-attachment conversation incorrectly default to diff view. The companion `useHasGitCommits` probe (`src/hooks/query/use-has-git-commits.ts`) then suppresses diff view for attached-but-empty cases (unborn HEAD, non-git workspace).
+- Collapsible thinking: `ThinkAction` events and LLM extended reasoning (`reasoning_content` / `thinking_blocks` on `ActionEvent`) are rendered as collapsible sections via `CollapsibleThinking` (`src/components/conversation-events/chat/event-message-components/collapsible-thinking.tsx`). Collapsed by default to keep the chat compact — the thinking is often in English regardless of the user's conversation language. The `getReasoningContent()` helper in `event-thought-helpers.ts` extracts the content, preferring `reasoning_content` (plain string) and falling back to Anthropic `thinking_blocks`. i18n keys: `THINKING$TITLE`, `THINKING$EXPAND`, `THINKING$COLLAPSE`. Tests: `__tests__/components/conversation-events/chat/event-message-think-action.test.tsx`.
+
- ESLint config (flat, ESLint 9): the project uses `eslint.config.js` (not `.eslintrc`) and runs on `[email protected]`, not 10. The constraint pinning us below 10 is `[email protected]`, which still calls `context.getFilename()` at rule-load time — that API was removed in ESLint 10 and `@eslint/compat`'s `fixupPluginRules` does NOT shim it. Don't try to bump eslint past 9 until eslint-plugin-react ships a v10-compatible release. Import rules come from `eslint-plugin-import-x` (the maintained fork of `eslint-plugin-import`) but are registered under both `import-x/` and `import/` prefixes via `plugins: { import: importXPlugin, ... }` so existing `// eslint-disable-next-line import/...` directives keep working. `linterOptions.reportUnusedDisableDirectives` is set to `"warn"` (not "off") so stale airbnb-era disable comments still surface in lint output without failing CI. The TS-overrides block has an `ignores: ["src/hooks/query/query-keys.ts"]` so the `no-restricted-syntax` rule banning raw `["settings", ...]` query keys doesn't fire on the file that defines the helpers themselves. No `.npmrc` / `legacy-peer-deps` flag is needed — all our plugins declare ESLint 9 peer compatibility.
diff --git a/__tests__/components/conversation-events/chat/event-message-think-action.test.tsx b/__tests__/components/conversation-events/chat/event-message-think-action.test.tsx
index 5cdacd53e1..b86d008984 100644
--- a/__tests__/components/conversation-events/chat/event-message-think-action.test.tsx
+++ b/__tests__/components/conversation-events/chat/event-message-think-action.test.tsx
@@ -1,5 +1,6 @@
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import { screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
import { EventMessage } from "#/components/conversation-events/chat/event-message";
import { useAgentState } from "#/hooks/use-agent-state";
import { AgentState } from "#/types/agent-state";
@@ -58,6 +59,7 @@ const createBashActionEvent = (
id: string,
command: string,
thoughtText: string,
+ overrides?: Partial<ActionEvent<ExecuteBashAction>>,
): ActionEvent<ExecuteBashAction> => ({
id,
timestamp: new Date().toISOString(),
@@ -83,6 +85,7 @@ const createBashActionEvent = (
},
llm_response_id: `response_${id}`,
security_risk: SecurityRisk.UNKNOWN,
+ ...overrides,
});
describe("EventMessage - ThinkAction rendering", () => {
@@ -118,7 +121,7 @@ describe("EventMessage - ThinkAction rendering", () => {
).not.toBeInTheDocument();
});
- it("should render ThinkAction thought as a normal chat message", () => {
+ it("should render ThinkAction as a collapsible section", () => {
const thinkEvent = createThinkActionEvent(
"think-2",
"Let me analyze the problem",
@@ -133,13 +136,41 @@ describe("EventMessage - ThinkAction rendering", () => {
/>,
);
- // The thought content should be displayed as regular text
+ // The collapsible thinking wrapper should exist
+ expect(screen.getByTestId("collapsible-thinking")).toBeInTheDocument();
+
+ // The thought content should NOT be visible initially (collapsed by default)
+ expect(
+ screen.queryByTestId("collapsible-thinking-content"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should expand ThinkAction content when toggle is clicked", async () => {
+ const user = userEvent.setup();
+ const thinkEvent = createThinkActionEvent(
+ "think-3",
+ "Let me analyze the problem",
+ );
+
+ renderWithProviders(
+ <EventMessage
+ event={thinkEvent}
+ messages={[thinkEvent]}
+ isLastMessage={false}
+ isInLast10Actions={false}
+ />,
+ );
+
+ // Click the toggle to expand
+ await user.click(screen.getByTestId("collapsible-thinking-toggle"));
+
+ // Now the content should be visible
+ expect(
+ screen.getByTestId("collapsible-thinking-content"),
+ ).toBeInTheDocument();
expect(
screen.getByText("Let me analyze the problem"),
).toBeInTheDocument();
-
- // It should NOT be inside a collapsible block (no expand button)
- expect(screen.queryByLabelText("Expand")).not.toBeInTheDocument();
});
it("should render ThoughtEventMessage for non-ThinkAction events", () => {
@@ -163,4 +194,61 @@ describe("EventMessage - ThinkAction rendering", () => {
screen.getByText("I need to run a command"),
).toBeInTheDocument();
});
+
+ it("should render reasoning_content as a collapsible section", () => {
+ const bashEvent = createBashActionEvent(
+ "bash-reasoning",
+ "echo hello",
+ "Running a command",
+ {
+ reasoning_content: "I need to think carefully about this step.",
+ },
+ );
+
+ renderWithProviders(
+ <EventMessage
+ event={bashEvent}
+ messages={[bashEvent]}
+ isLastMessage={false}
+ isInLast10Actions={false}
+ />,
+ );
+
+ // The collapsible thinking wrapper should exist for reasoning_content
+ expect(screen.getByTestId("collapsible-thinking")).toBeInTheDocument();
+
+ // The reasoning content should be hidden initially
+ expect(
+ screen.queryByText("I need to think carefully about this step."),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should render thinking_blocks as a collapsible section", () => {
+ const bashEvent = createBashActionEvent(
+ "bash-thinking-blocks",
+ "echo hello",
+ "Running a command",
+ {
+ thinking_blocks: [
+ {
+ type: "thinking",
+ thinking: "Extended thinking block content here.",
+ signature: "sig123",
+ },
+ ],
+ },
+ );
+
+ renderWithProviders(
+ <EventMessage
+ event={bashEvent}
+ messages={[bashEvent]}
+ isLastMessage={false}
+ isInLast10Actions={false}
+ />,
+ );
+
+ // The collapsible thinking wrapper should exist for thinking_blocks
+ expect(screen.getByTestId("collapsible-thinking")).toBeInTheDocument();
+ });
});
diff --git a/src/components/conversation-events/chat/event-message-components/collapsible-thinking.tsx b/src/components/conversation-events/chat/event-message-components/collapsible-thinking.tsx
new file mode 100644
index 0000000000..18e0ad2eb8
--- /dev/null
+++ b/src/components/conversation-events/chat/event-message-components/collapsible-thinking.tsx
@@ -0,0 +1,58 @@
+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 LightbulbIcon from "#/icons/lightbulb.svg?react";
+import { I18nKey } from "#/i18n/declaration";
+import { MarkdownRenderer } from "../../../features/markdown/markdown-renderer";
+
+interface CollapsibleThinkingProps {
+ /** The thinking / reasoning content to display when expanded. */
+ content: string;
+}
+
+/**
+ * Renders agent thinking or extended reasoning content inside a collapsible
+ * section. Collapsed by default so the chat stays compact — especially
+ * useful when the thinking language differs from the conversation language.
+ */
+export function CollapsibleThinking({ content }: CollapsibleThinkingProps) {
+ const { t } = useTranslation("openhands");
+ const [expanded, setExpanded] = React.useState(false);
+
+ if (!content.trim()) {
+ return null;
+ }
+
+ 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="collapsible-thinking"
+ >
+ <button
+ type="button"
+ onClick={() => setExpanded((prev) => !prev)}
+ aria-expanded={expanded}
+ aria-label={
+ expanded ? t(I18nKey.THINKING$COLLAPSE) : t(I18nKey.THINKING$EXPAND)
+ }
+ data-testid="collapsible-thinking-toggle"
+ className="w-full flex items-center gap-2 text-left cursor-pointer"
+ >
+ <Chevron className="h-4 w-4 fill-neutral-300 flex-shrink-0" />
+ <LightbulbIcon className="h-4 w-4 fill-neutral-300 flex-shrink-0" />
+ <span className="font-bold text-neutral-300">
+ {t(I18nKey.THINKING$TITLE)}
+ </span>
+ </button>
+
+ {expanded && (
+ <div className="mt-2 pl-6" data-testid="collapsible-thinking-content">
+ <MarkdownRenderer>{content}</MarkdownRenderer>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/conversation-events/chat/event-message.tsx b/src/components/conversation-events/chat/event-message.tsx
index e695dd0152..d9051437c1 100644
--- a/src/components/conversation-events/chat/event-message.tsx
+++ b/src/components/conversation-events/chat/event-message.tsx
@@ -21,16 +21,17 @@ 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 { PlanPreview } from "../../features/chat/plan-preview";
import { ErrorEventMessage } from "./event-message-components/error-event-message";
import { UserAssistantEventMessage } from "./event-message-components/user-assistant-event-message";
import { FinishEventMessage } from "./event-message-components/finish-event-message";
import { GenericEventMessageWrapper } from "./event-message-components/generic-event-message-wrapper";
import { ThoughtEventMessage } from "./event-message-components/thought-event-message";
+import { CollapsibleThinking } from "./event-message-components/collapsible-thinking";
import { HookExecutionEventMessage } from "./event-message-components/hook-execution-event-message";
import { createSkillReadyEvent } from "./event-content-helpers/create-skill-ready-event";
import { shouldShowPlanPreview } from "./hooks/use-plan-preview-events";
+import { getReasoningContent } from "./event-thought-helpers";
interface EventMessageProps {
event: OpenHandsEvent & { isFromPlanningAgent?: boolean };
@@ -128,7 +129,6 @@ const renderUserMessageWithSkillReady = (
}
};
-/* eslint-disable react/jsx-props-no-spreading */
export function EventMessage({
event,
messages,
@@ -186,24 +186,20 @@ export function EventMessage({
);
}
- // ThinkAction - render the thought as a normal chat message (not a collapsible block)
- // The thought content IS the action, so we use event.action.thought directly
- // instead of event.thought (which contains the raw tool call text).
+ // ThinkAction - render the thought inside a collapsible section so it
+ // doesn't dominate the chat, especially when the thinking language
+ // (usually English) differs from the conversation language.
if (isActionEvent(event) && event.action.kind === "ThinkAction") {
const thinkAction = event as ActionEvent<ThinkAction>;
- return (
- <ChatMessage
- type="agent"
- message={thinkAction.action.thought}
- isFromPlanningAgent={isFromPlanningAgent}
- />
- );
+ return <CollapsibleThinking content={thinkAction.action.thought} />;
}
// Action events - render thought + action (will be replaced by thought + observation)
if (isActionEvent(event)) {
+ const reasoningContent = getReasoningContent(event);
return (
<>
+ {reasoningContent && <CollapsibleThinking content={reasoningContent} />}
{!suppressThought && (
<ThoughtEventMessage
event={event}
@@ -256,8 +252,14 @@ export function EventMessage({
isActionEvent(correspondingAction) &&
correspondingAction.action.kind !== "ThinkAction";
+ const reasoningContent =
+ correspondingAction && isActionEvent(correspondingAction)
+ ? getReasoningContent(correspondingAction)
+ : "";
+
return (
<>
+ {reasoningContent && <CollapsibleThinking content={reasoningContent} />}
{shouldShowThought && (
<ThoughtEventMessage
event={correspondingAction}
diff --git a/src/components/conversation-events/chat/event-thought-helpers.ts b/src/components/conversation-events/chat/event-thought-helpers.ts
index 74b018c8a8..f9c7dcf295 100644
--- a/src/components/conversation-events/chat/event-thought-helpers.ts
+++ b/src/components/conversation-events/chat/event-thought-helpers.ts
@@ -1,4 +1,5 @@
import { ActionEvent, OpenHandsEvent } from "#/types/agent-server/core";
+import { ThinkingBlock } from "#/types/agent-server/core/base/event";
import {
isActionEvent,
isObservationEvent,
@@ -17,6 +18,28 @@ export const getActionThoughtText = (action: ActionEvent): string =>
.map((t) => t.text)
.join("\n");
+/**
+ * Extracts extended thinking / reasoning content from an `ActionEvent`.
+ *
+ * Prefers `reasoning_content` (a plain string produced by many reasoning
+ * 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 => {
+ if (action.reasoning_content) {
+ return action.reasoning_content;
+ }
+
+ if (action.thinking_blocks?.length) {
+ return action.thinking_blocks
+ .filter((b): b is ThinkingBlock => b.type === "thinking")
+ .map((b) => b.thinking)
+ .join("\n\n");
+ }
+
+ return "";
+};
+
export const hasNonEmptyThought = (action: ActionEvent): boolean =>
getActionThoughtText(action).trim().length > 0;
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index e8a6730181..6ad2dcdb70 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -25413,5 +25413,56 @@
"de": "Löschen",
"uk": "Видалити",
"ca": "Suprimeix"
+ },
+ "THINKING$TITLE": {
+ "en": "Thinking",
+ "ja": "思考中",
+ "zh-CN": "思考",
+ "zh-TW": "思考",
+ "ko-KR": "사고",
+ "de": "Denken",
+ "fr": "Réflexion",
+ "es": "Pensamiento",
+ "pt": "Pensamento",
+ "it": "Pensiero",
+ "no": "Tenkning",
+ "ar": "التفكير",
+ "tr": "Düşünme",
+ "uk": "Мислення",
+ "ca": "Pensament"
+ },
+ "THINKING$EXPAND": {
+ "en": "Expand thinking",
+ "ja": "思考を展開",
+ "zh-CN": "展开思考",
+ "zh-TW": "展開思考",
+ "ko-KR": "사고 펼치기",
+ "de": "Denken erweitern",
+ "fr": "Développer la réflexion",
+ "es": "Expandir pensamiento",
+ "pt": "Expandir pensamento",
+ "it": "Espandi pensiero",
+ "no": "Utvid tenkning",
+ "ar": "توسيع التفكير",
+ "tr": "Düşünmeyi genişlet",
+ "uk": "Розгорнути мислення",
+ "ca": "Expandir pensament"
+ },
+ "THINKING$COLLAPSE": {
+ "en": "Collapse thinking",
+ "ja": "思考を折りたたむ",
+ "zh-CN": "折叠思考",
+ "zh-TW": "摺疊思考",
+ "ko-KR": "사고 접기",
+ "de": "Denken einklappen",
+ "fr": "Réduire la réflexion",
+ "es": "Colapsar pensamiento",
+ "pt": "Recolher pensamento",
+ "it": "Comprimi pensiero",
+ "no": "Skjul tenkning",
+ "ar": "طي التفكير",
+ "tr": "Düşünmeyi daralt",
+ "uk": "Згорнути мислення",
+ "ca": "Plegar pensament"
}
}
diff --git a/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/reasoning-content-collapsed.png b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/reasoning-content-collapsed.png
new file mode 100644
index 0000000000..ba1f6be6ae
Binary files /dev/null and b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/reasoning-content-collapsed.png differ
diff --git a/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/reasoning-content-expanded.png b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/reasoning-content-expanded.png
new file mode 100644
index 0000000000..c847cbe5ad
Binary files /dev/null and b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/reasoning-content-expanded.png differ
diff --git a/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/think-action-collapsed.png b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/think-action-collapsed.png
new file mode 100644
index 0000000000..bedad3fb8f
Binary files /dev/null and b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/think-action-collapsed.png differ
diff --git a/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/think-action-expanded.png b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/think-action-expanded.png
new file mode 100644
index 0000000000..17ef873d7e
Binary files /dev/null and b/tests/e2e/__snapshots__/snapshots/collapsible-thinking.snapshot.spec.ts/chromium/think-action-expanded.png differ
diff --git a/tests/e2e/snapshots/collapsible-thinking.snapshot.spec.ts b/tests/e2e/snapshots/collapsible-thinking.snapshot.spec.ts
new file mode 100644
index 0000000000..c05a6377a3
--- /dev/null
+++ b/tests/e2e/snapshots/collapsible-thinking.snapshot.spec.ts
@@ -0,0 +1,304 @@
+import { test, expect, Page } from "@playwright/test";
+
+/**
+ * Visual snapshot tests for the CollapsibleThinking component.
+ *
+ * These tests navigate to a conversation in the mock dev server, inject
+ * synthetic events into the event store, and capture screenshots of the
+ * collapsible thinking sections in both collapsed and expanded states.
+ *
+ * The mock dev server (VITE_MOCK_API=true) uses MSW service workers to
+ * handle API requests. We rely on MSW for conversations, settings, etc.
+ * and only inject events directly into the Zustand store.
+ *
+ * To update baselines after intentional UI changes:
+ * npm run test:e2e:snapshots:update
+ */
+
+// Use mock conversation ID "1" which is pre-defined in MSW handlers
+const CONVERSATION_ID = "1";
+
+/** ThinkAction event with thinking content */
+const THINK_ACTION_EVENT = {
+ id: "think-event-1",
+ timestamp: "2026-01-01T00:00:01.000Z",
+ source: "agent",
+ thought: [
+ {
+ type: "text",
+ text: 'think: {"thought": "I need to analyze the codebase structure first. Let me look at the directory layout and understand the project architecture before making any changes."}',
+ },
+ ],
+ reasoning_content: null,
+ thinking_blocks: [],
+ action: {
+ kind: "ThinkAction",
+ thought:
+ "I need to analyze the codebase structure first. Let me look at the directory layout and understand the project architecture before making any changes.",
+ },
+ tool_name: "think",
+ tool_call_id: "call_think_1",
+ tool_call: {
+ id: "call_think_1",
+ type: "function",
+ function: {
+ name: "think",
+ arguments: JSON.stringify({
+ thought:
+ "I need to analyze the codebase structure first. Let me look at the directory layout and understand the project architecture before making any changes.",
+ }),
+ },
+ },
+ llm_response_id: "response_1",
+ security_risk: "unknown",
+};
+
+/** Bash action event with reasoning_content (extended thinking) */
+const BASH_WITH_REASONING_EVENT = {
+ id: "bash-event-1",
+ timestamp: "2026-01-01T00:00:02.000Z",
+ source: "agent",
+ thought: [
+ {
+ type: "text",
+ text: "Let me list the project files to understand the structure.",
+ },
+ ],
+ reasoning_content:
+ "The user wants to understand the project. I should start by listing the files in the root directory. This will give us a high-level overview of the codebase. Then I can dive deeper into specific areas based on what we find.",
+ thinking_blocks: [],
+ action: {
+ kind: "ExecuteBashAction",
+ command: "ls -la",
+ is_input: false,
+ timeout: null,
+ reset: false,
+ },
+ tool_name: "execute_bash",
+ tool_call_id: "call_bash_1",
+ tool_call: {
+ id: "call_bash_1",
+ type: "function",
+ function: {
+ name: "execute_bash",
+ arguments: JSON.stringify({ command: "ls -la" }),
+ },
+ },
+ llm_response_id: "response_2",
+ security_risk: "unknown",
+};
+
+/** User message event */
+const USER_MESSAGE_EVENT = {
+ id: "user-msg-1",
+ timestamp: "2026-01-01T00:00:00.000Z",
+ source: "user",
+ role: "user",
+ payload: [{ type: "text", text: "Help me understand this project" }],
+};
+
+/**
+ * Dismisses the analytics consent modal if it appears.
+ * The MSW mock settings don't include user_consents_to_analytics, so
+ * the consent modal may appear on first load.
+ */
+async function dismissConsentModal(page: Page) {
+ const confirmButton = page.getByRole("button", {
+ name: "Confirm preferences",
+ });
+ try {
+ await confirmButton.waitFor({ state: "visible", timeout: 5000 });
+ await confirmButton.click();
+ await page
+ .getByRole("dialog", { name: "Help improve OpenHands" })
+ .waitFor({ state: "hidden", timeout: 5000 });
+ } catch {
+ // Modal didn't appear — that's fine
+ }
+}
+
+/**
+ * Inject events into the event store via the exposed Zustand API.
+ */
+async function injectEvents(page: Page, events: unknown[]) {
+ await page.evaluate((evts) => {
+ const store = (
+ window as unknown as {
+ __OH_EVENT_STORE__?: {
+ getState: () => { addEvents: (e: unknown[]) => void };
+ };
+ }
+ ).__OH_EVENT_STORE__;
+ if (store) {
+ store.getState().addEvents(evts);
+ }
+ }, events);
+ // Wait for React to re-render
+ await page.waitForTimeout(500);
+}
+
+/**
+ * Navigate to a conversation page and wait for the chat interface to load.
+ * Uses mock conversation "1" which exists in the MSW handlers.
+ */
+async function navigateToConversation(page: Page) {
+ // Skip onboarding
+ await page.addInitScript(() => {
+ window.localStorage.setItem("openhands-onboarded", "true");
+ });
+
+ // Stub WebSocket to prevent connection errors
+ await page.addInitScript(() => {
+ const noop = () => {};
+ class StubWebSocket extends EventTarget {
+ static CONNECTING = 0;
+ static OPEN = 1;
+ static CLOSING = 2;
+ static CLOSED = 3;
+ readyState = StubWebSocket.OPEN;
+ url: string;
+ protocol = "";
+ extensions = "";
+ bufferedAmount = 0;
+ binaryType: BinaryType = "blob";
+ onopen: ((ev: Event) => void) | null = null;
+ onclose: ((ev: CloseEvent) => void) | null = null;
+ onmessage: ((ev: MessageEvent) => void) | null = null;
+ onerror: ((ev: Event) => void) | null = null;
+ constructor(url: string | URL) {
+ super();
+ this.url = typeof url === "string" ? url : url.toString();
+ setTimeout(() => {
+ const evt = new Event("open");
+ this.onopen?.(evt);
+ this.dispatchEvent(evt);
+ }, 10);
+ }
+ send = noop;
+ close = noop;
+ CONNECTING = StubWebSocket.CONNECTING;
+ OPEN = StubWebSocket.OPEN;
+ CLOSING = StubWebSocket.CLOSING;
+ CLOSED = StubWebSocket.CLOSED;
+ }
+ (window as unknown as { WebSocket: unknown }).WebSocket =
+ StubWebSocket as unknown as typeof WebSocket;
+ });
+
+ await page.goto(`/conversations/${CONVERSATION_ID}`, {
+ waitUntil: "domcontentloaded",
+ });
+ await dismissConsentModal(page);
+
+ const chatInterface = page.getByTestId("chat-interface");
+ await expect(chatInterface).toBeVisible({ timeout: 20000 });
+ return chatInterface;
+}
+
+test.describe("Collapsible Thinking Visual Snapshots", () => {
+ // Run serially: the conversation page + WebSocket stub is heavier than
+ // static pages, and parallel workers hitting the shared dev server can
+ // cause intermittent load failures.
+ test.describe.configure({ mode: "serial" });
+ test.setTimeout(60000);
+
+ test("ThinkAction renders as collapsed section", async ({ page }) => {
+ const chatInterface = await navigateToConversation(page);
+
+ // Inject events
+ await injectEvents(page, [USER_MESSAGE_EVENT, THINK_ACTION_EVENT]);
+
+ // Verify the collapsible thinking section is rendered
+ const collapsibleThinking = page.getByTestId("collapsible-thinking");
+ await expect(collapsibleThinking).toBeVisible({ timeout: 5000 });
+
+ // The content should be collapsed (not visible)
+ const content = page.getByTestId("collapsible-thinking-content");
+ await expect(content).toHaveCount(0);
+
+ // Snapshot: collapsed state
+ await expect(chatInterface).toHaveScreenshot(
+ "think-action-collapsed.png",
+ {
+ maxDiffPixelRatio: 0.01,
+ animations: "disabled",
+ },
+ );
+ });
+
+ test("ThinkAction expands on click", async ({ page }) => {
+ const chatInterface = await navigateToConversation(page);
+
+ await injectEvents(page, [USER_MESSAGE_EVENT, THINK_ACTION_EVENT]);
+
+ const toggle = page.getByTestId("collapsible-thinking-toggle");
+ await expect(toggle).toBeVisible({ timeout: 5000 });
+
+ // Click to expand
+ await toggle.click();
+
+ // Content should now be visible
+ const content = page.getByTestId("collapsible-thinking-content");
+ await expect(content).toBeVisible({ timeout: 5000 });
+
+ // Snapshot: expanded state
+ await expect(chatInterface).toHaveScreenshot(
+ "think-action-expanded.png",
+ {
+ maxDiffPixelRatio: 0.01,
+ animations: "disabled",
+ },
+ );
+ });
+
+ test("Reasoning content renders as collapsed section with action", async ({
+ page,
+ }) => {
+ const chatInterface = await navigateToConversation(page);
+
+ await injectEvents(page, [
+ USER_MESSAGE_EVENT,
+ BASH_WITH_REASONING_EVENT,
+ ]);
+
+ // Verify both the collapsible section and the action event are present
+ const collapsibleThinking = page.getByTestId("collapsible-thinking");
+ await expect(collapsibleThinking).toBeVisible({ timeout: 5000 });
+
+ // Snapshot: reasoning content collapsed alongside the bash action
+ await expect(chatInterface).toHaveScreenshot(
+ "reasoning-content-collapsed.png",
+ {
+ maxDiffPixelRatio: 0.01,
+ animations: "disabled",
+ },
+ );
+ });
+
+ test("Reasoning content expands on click", async ({ page }) => {
+ const chatInterface = await navigateToConversation(page);
+
+ await injectEvents(page, [
+ USER_MESSAGE_EVENT,
+ BASH_WITH_REASONING_EVENT,
+ ]);
+
+ const toggle = page.getByTestId("collapsible-thinking-toggle");
+ await expect(toggle).toBeVisible({ timeout: 5000 });
+
+ // Click to expand
+ await toggle.click();
+
+ const content = page.getByTestId("collapsible-thinking-content");
+ await expect(content).toBeVisible({ timeout: 5000 });
+
+ // Snapshot: reasoning content expanded
+ await expect(chatInterface).toHaveScreenshot(
+ "reasoning-content-expanded.png",
+ {
+ maxDiffPixelRatio: 0.01,
+ animations: "disabled",
+ },
+ );
+ });
+});