π OpenHands: AI-Driven Development
fix(chat): avoid re-rendering unchanged historical Markdown (#17015)
Gali1c5fb85fa71f
diff --git a/__tests__/components/conversation-events/chat/event-message-plan-preview.test.tsx b/__tests__/components/conversation-events/chat/event-message-plan-preview.test.tsxindex bd85783666..4647c99503 100644--- a/__tests__/components/conversation-events/chat/event-message-plan-preview.test.tsx+++ b/__tests__/components/conversation-events/chat/event-message-plan-preview.test.tsx@@ -122,6 +122,62 @@ describe("EventMessage - PlanPreview rendering", () => {expect(container.firstChild).toBeNull();});+ it("prefers an explicit showPlanPreview value over the legacy set", () => {+ const event = createPlanningObservationEvent("plan-obs-1");+ const planPreviewEventIds = new Set(["plan-obs-1"]);++ const { container } = renderWithProviders(+ <EventMessage+ event={event}+ messages={[]}+ isLastMessage={false}+ isInLast10Actions={false}+ planPreviewEventIds={planPreviewEventIds}+ showPlanPreview={false}+ />,+ );++ expect(screen.queryByTestId("plan-preview")).not.toBeInTheDocument();+ expect(container.firstChild).toBeNull();+ });++ it("rerenders when the memoized wrapper stops being the live tail", () => {+ const event = createPlanningObservationEvent("plan-obs-1");+ vi.mocked(usePlanningAgentState).mockReturnValue({+ localPlanningConversationId: "planner-1",+ curPlanningAgentState: AgentState.RUNNING,+ isPlanningAgentRunning: true,+ });++ const { rerender } = renderWithProviders(+ <EventMessage+ event={event}+ correspondingAction={null}+ isLastMessage+ isInLast10Actions+ showPlanPreview+ />,+ );+ expect(screen.getByTestId("plan-preview")).toHaveAttribute(+ "data-is-streaming",+ "true",+ );++ rerender(+ <EventMessage+ event={event}+ correspondingAction={null}+ isLastMessage={false}+ isInLast10Actions+ showPlanPreview+ />,+ );+ expect(screen.getByTestId("plan-preview")).toHaveAttribute(+ "data-is-streaming",+ "false",+ );+ });+it("should use planContent from conversation store", () => {const event = createPlanningObservationEvent("plan-obs-1");const planPreviewEventIds = new Set(["plan-obs-1"]);diff --git a/__tests__/components/conversation-events/chat/messages-markdown-render-stability.test.tsx b/__tests__/components/conversation-events/chat/messages-markdown-render-stability.test.tsxnew file mode 100644index 0000000000..f258234c41--- /dev/null+++ b/__tests__/components/conversation-events/chat/messages-markdown-render-stability.test.tsx@@ -0,0 +1,111 @@+import type { ReactNode } from "react";+import { screen } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { renderWithProviders } from "test-utils";+import { Messages } from "#/components/conversation-events/chat/messages";+import type { MessageEvent } from "#/types/agent-server/core";+import type { StreamingDeltaEvent } from "#/types/agent-server/core/events/streaming-delta-event";++const { recordSyntaxHighlight } = vi.hoisted(() => ({+ recordSyntaxHighlight: vi.fn(),+}));++vi.mock("#/components/features/markdown/syntax-highlighter", () => ({+ SyntaxHighlighter: ({ children }: { children?: ReactNode }) => {+ recordSyntaxHighlight();+ return <code>{children}</code>;+ },+}));++vi.mock(+ "#/components/shared/buttons/conversation-confirmation-buttons",+ () => ({+ ConversationConfirmationButtons: () => (+ <span data-testid="confirmation-marker" />+ ),+ }),+);++const makeAgentMessage = (id: string, text: string): MessageEvent => ({+ id,+ timestamp: "2026-08-30T00:00:00Z",+ source: "agent",+ llm_message: {+ role: "assistant",+ content: [{ type: "text", text }],+ },+ activated_skills: [],+ extended_content: [],+});++const makeStreamingDelta = (content: string): StreamingDeltaEvent => ({+ id: "live-stream",+ timestamp: "2026-08-30T00:00:01Z",+ source: "agent",+ kind: "StreamingDeltaEvent",+ content,+ reasoning_content: null,+});++const codeHeavyMessage = (index: number) =>+ [+ `Historical response ${index}`,+ "```javascript",+ ...Array.from(+ { length: 50 },+ (_, line) => `const value${line} = ${index + line};`,+ ),+ "```",+ ].join("\n");++describe("Messages markdown render stability", () => {+ beforeEach(() => {+ recordSyntaxHighlight.mockClear();+ });++ it("does not re-render historical code blocks when the live tail changes", () => {+ const history = Array.from({ length: 20 }, (_, index) =>+ makeAgentMessage(`history-${index}`, codeHeavyMessage(index)),+ );++ const { rerender } = renderWithProviders(+ <Messages messages={history} allEvents={history} />,+ );++ expect(recordSyntaxHighlight).toHaveBeenCalledTimes(history.length);+ expect(screen.getAllByTestId("agent-message").at(-1)).toHaveTextContent(+ "Historical response 19",+ );+ recordSyntaxHighlight.mockClear();++ const durableTail = makeAgentMessage("durable-tail", "Plain tail message");+ const withDurableTail = [...history, durableTail];+ rerender(+ <Messages messages={withDurableTail} allEvents={withDurableTail} />,+ );+ expect(screen.getAllByTestId("agent-message").at(-1)).toHaveTextContent(+ "Plain tail message",+ );++ const firstStreamingTail = makeStreamingDelta("Live update 0");+ rerender(+ <Messages+ messages={[...withDurableTail, firstStreamingTail]}+ allEvents={[...withDurableTail, firstStreamingTail]}+ />,+ );++ for (let update = 1; update <= 5; update += 1) {+ const streamingTail = makeStreamingDelta(`Live update ${update}`);+ rerender(+ <Messages+ messages={[...withDurableTail, streamingTail]}+ allEvents={[...withDurableTail, streamingTail]}+ />,+ );+ }++ expect(screen.getByText("Live update 5")).toBeInTheDocument();+ expect(recordSyntaxHighlight).not.toHaveBeenCalled();+ });+});diff --git a/__tests__/components/conversation-events/chat/messages-stable-event-props.test.tsx b/__tests__/components/conversation-events/chat/messages-stable-event-props.test.tsxnew file mode 100644index 0000000000..9bfbb21d62--- /dev/null+++ b/__tests__/components/conversation-events/chat/messages-stable-event-props.test.tsx@@ -0,0 +1,123 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ createOtherActionEvent,+ createPlanningObservationEvent,+ createUserMessageEvent,+ renderWithProviders,+} from "test-utils";+import { Messages } from "#/components/conversation-events/chat/messages";+import type { ActionEvent, OpenHandsEvent } from "#/types/agent-server/core";++const { recordEventMessage } = vi.hoisted(() => ({+ recordEventMessage: vi.fn(),+}));++interface CapturedProps {+ event: OpenHandsEvent;+ correspondingAction: ActionEvent | null;+ isLastMessage: boolean;+ isInLast10Actions: boolean;+ showPlanPreview: boolean;+ messages?: OpenHandsEvent[];+ planPreviewEventIds?: Set<string>;+}++vi.mock("#/components/conversation-events/chat/event-message", () => ({+ EventMessage: (props: CapturedProps) => {+ recordEventMessage(props);+ return <div data-testid={`event-${props.event.id}`} />;+ },+}));++const latestPropsFor = (eventId: string): CapturedProps => {+ const props = recordEventMessage.mock.calls+ .map(([value]) => value as CapturedProps)+ .reverse()+ .find(({ event }) => event.id === eventId);+ if (!props) throw new Error(`No EventMessage props recorded for ${eventId}`);+ return props;+};++const makeBashObservation = (id: string, actionId: string): OpenHandsEvent =>+ ({+ id,+ timestamp: "2026-08-30T00:00:00Z",+ source: "environment",+ tool_name: "execute_bash",+ tool_call_id: `call-${actionId}`,+ action_id: actionId,+ observation: {+ kind: "ExecuteBashObservation",+ content: [{ type: "text", text: "ok" }],+ command: "echo test",+ exit_code: 0,+ error: false,+ timeout: false,+ metadata: {},+ },+ }) as OpenHandsEvent;++describe("Messages stable EventMessage props", () => {+ beforeEach(() => {+ recordEventMessage.mockClear();+ });++ it("derives positional flags that legitimately change across a tail append", () => {+ const initial = Array.from({ length: 12 }, (_, index) =>+ createUserMessageEvent(`message-${index}`),+ );+ const { rerender } = renderWithProviders(+ <Messages messages={initial} allEvents={initial} />,+ );++ expect(latestPropsFor("message-2").isInLast10Actions).toBe(true);+ expect(latestPropsFor("message-11").isLastMessage).toBe(true);++ recordEventMessage.mockClear();+ const appended = [...initial, createUserMessageEvent("message-12")];+ rerender(<Messages messages={appended} allEvents={appended} />);++ expect(latestPropsFor("message-2").isInLast10Actions).toBe(false);+ expect(latestPropsFor("message-11").isLastMessage).toBe(false);+ expect(latestPropsFor("message-12").isLastMessage).toBe(true);+ expect(latestPropsFor("message-0").messages).toBeUndefined();+ expect(latestPropsFor("message-0").planPreviewEventIds).toBeUndefined();+ });++ it("refreshes an observation when its corresponding action is backfilled", () => {+ const observation = makeBashObservation("observation-1", "action-1");+ const messages = [observation];+ const { rerender } = renderWithProviders(+ <Messages messages={messages} allEvents={messages} />,+ );++ expect(latestPropsFor("observation-1").correspondingAction).toBeNull();++ recordEventMessage.mockClear();+ const action = createOtherActionEvent("action-1");+ rerender(+ <Messages messages={messages} allEvents={[action, observation]} />,+ );++ expect(latestPropsFor("observation-1").correspondingAction).toBe(action);+ });++ it("moves a plan preview to the last observation in its phase", () => {+ const user = createUserMessageEvent("user-1");+ const firstPlan = createPlanningObservationEvent("plan-1", "action-1");+ const initial = [user, firstPlan];+ const { rerender } = renderWithProviders(+ <Messages messages={initial} allEvents={initial} />,+ );++ expect(latestPropsFor("plan-1").showPlanPreview).toBe(true);++ recordEventMessage.mockClear();+ const secondPlan = createPlanningObservationEvent("plan-2", "action-2");+ const updated = [...initial, secondPlan];+ rerender(<Messages messages={updated} allEvents={updated} />);++ expect(latestPropsFor("plan-1").showPlanPreview).toBe(false);+ expect(latestPropsFor("plan-2").showPlanPreview).toBe(true);+ });+});diff --git a/src/components/conversation-events/chat/event-message-components/user-assistant-event-message.tsx b/src/components/conversation-events/chat/event-message-components/user-assistant-event-message.tsxindex 64d5e4b931..d3792656e8 100644--- a/src/components/conversation-events/chat/event-message-components/user-assistant-event-message.tsx+++ b/src/components/conversation-events/chat/event-message-components/user-assistant-event-message.tsx@@ -23,7 +23,7 @@ interface UserAssistantEventMessageProps {isFromPlanningAgent: boolean;}-export function UserAssistantEventMessage({+function UserAssistantEventMessageComponent({event,isFromPlanningAgent,}: UserAssistantEventMessageProps) {@@ -130,3 +130,10 @@ export function UserAssistantEventMessage({</>);}++// Appending at the live tail keeps historical event objects and these scalar+// rendering inputs stable. Context and store subscriptions still propagate,+// while unchanged message wrappers avoid reconciling their large DOM subtrees.+export const UserAssistantEventMessage = React.memo(+ UserAssistantEventMessageComponent,+);diff --git a/src/components/conversation-events/chat/event-message.tsx b/src/components/conversation-events/chat/event-message.tsxindex e35a4df71c..2fea757370 100644--- a/src/components/conversation-events/chat/event-message.tsx+++ b/src/components/conversation-events/chat/event-message.tsx@@ -40,11 +40,19 @@ import { getReasoningContent, splitInlineThink } from "./event-thought-helpers";interface EventMessageProps {event: OpenHandsEvent & { isFromPlanningAgent?: boolean };- messages: OpenHandsEvent[];+ /** @deprecated Prefer the stable correspondingAction prop. */+ messages?: OpenHandsEvent[];+ /**+ * The action paired with an observation. null means the caller performed+ * the lookup and found no action; undefined keeps legacy messages lookup.+ */+ correspondingAction?: ActionEvent | null;isLastMessage: boolean;isInLast10Actions: boolean;/** Set of event IDs that should render PlanPreview (one per user message phase) */planPreviewEventIds?: Set<string>;+ /** Stable per-event replacement for planPreviewEventIds. */+ showPlanPreview?: boolean;/*** When true, do not render the inline `ThoughtEventMessage` for action /* observation events. The caller is expected to render the thought@@ -163,16 +171,18 @@ function PlanningObservationPreview({);}-export function EventMessage({+function EventMessageComponent({event,messages,+ correspondingAction: suppliedCorrespondingAction,isLastMessage,isInLast10Actions,planPreviewEventIds,+ showPlanPreview,suppressThought = false,}: EventMessageProps) {const { data: config } = useConfig();- const { planContent } = useConversationStore();+ const planContent = useConversationStore((state) => state.planContent);const { curAgentState } = useAgentState();// Planner-running state is folded in by PlanningObservationPreview below,@@ -290,8 +300,10 @@ export function EventMessage({// Only show PlanPreview if this event is marked as the one to display// (last PlanningFileEditorObservation in its phase)if (- planPreviewEventIds &&- shouldShowPlanPreview(event.id, planPreviewEventIds)+ showPlanPreview ??+ (planPreviewEventIds+ ? shouldShowPlanPreview(event.id, planPreviewEventIds)+ : false)) {return (<PlanningObservationPreview@@ -307,9 +319,12 @@ export function EventMessage({}// Find the action that this observation is responding to- const correspondingAction = messages.find(- (msg) => isActionEvent(msg) && msg.id === event.action_id,- );+ const correspondingAction =+ suppliedCorrespondingAction === undefined+ ? messages?.find(+ (msg) => isActionEvent(msg) && msg.id === event.action_id,+ )+ : (suppliedCorrespondingAction ?? undefined);// Skip ThoughtEventMessage for ThinkAction (thought IS the action)const shouldShowThought =@@ -373,3 +388,9 @@ export function EventMessage({<GenericEventMessageWrapper event={event} isLastMessage={isLastMessage} />);}++// Messages passes stable event-specific lookup results, so an appended tail+// can update only the wrappers whose event or positional state really changed.+// Context and store subscriptions inside this component still bypass memo.+export const EventMessage = React.memo(EventMessageComponent);+EventMessage.displayName = "EventMessage";diff --git a/src/components/conversation-events/chat/messages.tsx b/src/components/conversation-events/chat/messages.tsxindex 367eb60574..9a1bceb2d6 100644--- a/src/components/conversation-events/chat/messages.tsx+++ b/src/components/conversation-events/chat/messages.tsx@@ -1,5 +1,9 @@import React from "react";-import { OpenHandsEvent } from "#/types/agent-server/core";+import { ActionEvent, OpenHandsEvent } from "#/types/agent-server/core";+import {+ isActionEvent,+ isObservationEvent,+} from "#/types/agent-server/type-guards";import { EventMessage } from "./event-message";import { usePlanPreviewEvents } from "./hooks/use-plan-preview-events";import { groupEvents } from "./group-events";@@ -25,6 +29,18 @@ export const Messages: React.FC<MessagesProps> = React.memo(// This ensures only one preview per user message "phase"const planPreviewEventIds = usePlanPreviewEvents(allEvents);+ // EventMessage used to receive the complete allEvents array and the plan+ // Set, so every append changed every historical item's shallow props.+ // Derive the two event-specific values once and keep unchanged wrappers+ // eligible for React.memo without removing allEvents from grouping logic.+ const actionById = React.useMemo(() => {+ const actions = new Map<string, ActionEvent>();+ for (const event of allEvents) {+ if (isActionEvent(event)) actions.set(event.id, event);+ }+ return actions;+ }, [allEvents]);+// Set of event ids that have a /model entry anchored to them β used to// avoid mounting <ModelMessages> for every event (the component would// otherwise early-return null).@@ -68,10 +84,14 @@ export const Messages: React.FC<MessagesProps> = React.memo(<EventMessagekey={event.id}event={event}- messages={allEvents}+ correspondingAction={+ isObservationEvent(event) && event.action_id+ ? (actionById.get(event.action_id) ?? null)+ : null+ }isLastMessage={messages.length - 1 === index}isInLast10Actions={messages.length - 1 - index < 10}- planPreviewEventIds={planPreviewEventIds}+ showPlanPreview={event.id ? planPreviewEventIds.has(event.id) : false}suppressThought={suppressThought}/>);diff --git a/src/components/features/markdown/markdown-renderer.tsx b/src/components/features/markdown/markdown-renderer.tsxindex 0eeac25ae0..96003b23e6 100644--- a/src/components/features/markdown/markdown-renderer.tsx+++ b/src/components/features/markdown/markdown-renderer.tsx@@ -1,3 +1,4 @@+import React from "react";import Markdown, { Components } from "react-markdown";import remarkGfm from "remark-gfm";import remarkBreaks from "remark-breaks";@@ -131,7 +132,7 @@ interface MarkdownRendererProps {* - includeHeadings: adds h1-h6 heading components* - components prop: allows custom overrides or additional components*/-export function MarkdownRenderer({+function MarkdownRendererComponent({children,content,components: customComponents,@@ -187,3 +188,8 @@ export function MarkdownRenderer({</div>);}++// Parsing markdown and highlighting fenced code are expensive for long chat+// histories. Keep unchanged bodies stable while their surrounding message+// wrappers respond to tail, grouping, and conversation-state updates.+export const MarkdownRenderer = React.memo(MarkdownRendererComponent);diff --git a/tests/e2e/conversation-markdown-render-performance.spec.ts b/tests/e2e/conversation-markdown-render-performance.spec.tsnew file mode 100644index 0000000000..b6175743af--- /dev/null+++ b/tests/e2e/conversation-markdown-render-performance.spec.ts@@ -0,0 +1,358 @@+import { expect, test, type Page } from "@playwright/test";++type ProbeMeasurement = {+ storeCallMs: number;+ composerLatencyMs: number;+};++type FixtureMeasurement = {+ append: ProbeMeasurement;+ streaming: ProbeMeasurement[];+ tokenSpans: number;+ elements: number;+ longTasks: number[];+ codePreserved: boolean;+};++type ContextMeasurement = {+ context: number;+ control: FixtureMeasurement;+ longHistory: FixtureMeasurement;+};++const FIXTURE_CONVERSATION_ID = "pagination-local";+const BASE_URL = "http://localhost:3001/";+const RUN_PERFORMANCE_ACCEPTANCE =+ process.env.RUN_CONVERSATION_MARKDOWN_PERF === "1";++const median = (values: number[]) => {+ const sorted = [...values].sort((a, b) => a - b);+ const middle = Math.floor(sorted.length / 2);+ return sorted.length % 2 === 0+ ? (sorted[middle - 1] + sorted[middle]) / 2+ : sorted[middle];+};++async function runFixture(+ page: Page,+ historyCount: number,+ lineCount: number,+): Promise<FixtureMeasurement> {+ return page.evaluate(+ async ({ conversationId, fixtureHistoryCount, fixtureLineCount }) => {+ type FixtureStore = {+ getState: () => {+ clearEventsForConversation: (id: string) => void;+ addEvents: (events: Array<Record<string, unknown>>) => void;+ addEvent: (event: Record<string, unknown>) => void;+ };+ };++ const store = (window as unknown as { __OH_EVENT_STORE__?: FixtureStore })+ .__OH_EVENT_STORE__;+ if (!store) {+ throw new Error(+ "The performance fixture requires the mock-build event store seam.",+ );+ }++ const raf = () =>+ new Promise<void>((resolve) =>+ window.requestAnimationFrame(() => resolve()),+ );+ const code = Array.from(+ { length: fixtureLineCount },+ (_, line) =>+ "const item_" ++ String(line).padStart(4, "0") ++ ' = { alpha: "value-' ++ line ++ '", count: ' ++ line ++ ", active: true }; // deterministic fixture",+ ).join("\n");+ const base = Date.UTC(2026, 7, 29, 12, 0, 0);+ const events: Array<Record<string, unknown>> = [];++ for (let index = 0; index < fixtureHistoryCount; index += 1) {+ events.push({+ id: "fixture-user-" + index,+ timestamp: new Date(base + index * 2000).toISOString(),+ source: "user",+ llm_message: {+ role: "user",+ content: [+ {+ type: "text",+ text: "Run deterministic tool step " + index,+ },+ ],+ },+ activated_skills: [],+ extended_content: [],+ });+ events.push({+ id: "fixture-agent-" + index,+ timestamp: new Date(base + index * 2000 + 1000).toISOString(),+ source: "agent",+ llm_message: {+ role: "assistant",+ content: [+ {+ type: "text",+ text: [+ "Tool output " + index,+ "",+ "```javascript",+ code,+ "```",+ ].join("\n"),+ },+ ],+ },+ activated_skills: [],+ extended_content: [],+ });+ }++ store.getState().clearEventsForConversation(conversationId);+ store.getState().addEvents(events);++ const expectedTokenSpans = fixtureHistoryCount * fixtureLineCount * 17;+ const renderDeadline = performance.now() + 30_000;+ while (+ document.querySelectorAll("span.token").length < expectedTokenSpans+ ) {+ if (performance.now() > renderDeadline) {+ throw new Error(+ "Timed out mounting the highlighted conversation fixture.",+ );+ }+ await raf();+ }+ await raf();++ const longTasks: number[] = [];+ const observer = new PerformanceObserver((list) => {+ for (const entry of list.getEntries()) {+ longTasks.push(Number(entry.duration.toFixed(1)));+ }+ });+ observer.observe({ type: "longtask", buffered: true });++ const probe = (event: Record<string, unknown>) => {+ const started = performance.now();+ const composerProbe = new Promise<number>((resolve) => {+ window.setTimeout(() => {+ const input = document.querySelector<HTMLElement>(+ '[data-testid="chat-input"]',+ );+ input?.focus();+ resolve(Number((performance.now() - started).toFixed(1)));+ }, 0);+ });+ const storeStarted = performance.now();+ store.getState().addEvent(event);+ const storeCallMs = Number(+ (performance.now() - storeStarted).toFixed(1),+ );+ return composerProbe.then((composerLatencyMs) => ({+ storeCallMs,+ composerLatencyMs,+ }));+ };++ const append = await probe({+ id: "fixture-plain-tail",+ timestamp: new Date(Date.UTC(2026, 7, 29, 14, 0, 0)).toISOString(),+ source: "agent",+ llm_message: {+ role: "assistant",+ content: [{ type: "text", text: "Final plain-text response." }],+ },+ activated_skills: [],+ extended_content: [],+ });+ await raf();++ const streaming: ProbeMeasurement[] = [];+ for (let update = 0; update < 5; update += 1) {+ streaming.push(+ await probe({+ id: "fixture-stream-" + update,+ timestamp: new Date(+ Date.UTC(2026, 7, 29, 15, 0, update),+ ).toISOString(),+ source: "agent",+ kind: "StreamingDeltaEvent",+ content: " streaming-" + update,+ reasoning_content: null,+ }),+ );+ await raf();+ }++ await raf();+ // longtask entries are delivered in a later task than the work that+ // produced them, and disconnect() drops whatever is still queued.+ await new Promise<void>((resolve) => window.setTimeout(resolve, 0));+ observer.disconnect();+ const lastLine =+ "const item_" + String(fixtureLineCount - 1).padStart(4, "0");++ return {+ append,+ streaming,+ tokenSpans: document.querySelectorAll("span.token").length,+ elements: document.getElementsByTagName("*").length,+ longTasks,+ codePreserved: document.body.textContent?.includes(lastLine) ?? false,+ };+ },+ {+ conversationId: FIXTURE_CONVERSATION_ID,+ fixtureHistoryCount: historyCount,+ fixtureLineCount: lineCount,+ },+ );+}++test("keeps code-heavy history responsive across tail updates", async ({+ browser,+ browserName,+}, testInfo) => {+ test.skip(+ !RUN_PERFORMANCE_ACCEPTANCE,+ "Set RUN_CONVERSATION_MARKDOWN_PERF=1 to run the isolated wall-clock benchmark.",+ );+ test.skip(+ browserName !== "chromium",+ "Performance acceptance is defined against Chromium.",+ );+ test.setTimeout(240_000);++ const measurements: ContextMeasurement[] = [];+ for (let contextIndex = 0; contextIndex < 3; contextIndex += 1) {+ const context = await browser.newContext({ baseURL: BASE_URL });+ await context.addInitScript(() => {+ window.localStorage.setItem("analytics-consent", "false");+ window.localStorage.setItem("openhands-telemetry-consent", "denied");+ window.localStorage.setItem("openhands-telemetry-first-use", "true");+ window.localStorage.setItem("openhands-onboarded", "1");+ window.localStorage.setItem(+ "openhands-backends",+ JSON.stringify([+ {+ id: "default-local",+ name: "Local",+ host: window.location.origin,+ apiKey: "",+ kind: "local",+ },+ ]),+ );+ window.localStorage.setItem(+ "openhands-active-backend",+ JSON.stringify({ backendId: "default-local", orgId: null }),+ );+ });++ const page = await context.newPage();+ await page.goto("/conversations/" + FIXTURE_CONVERSATION_ID, {+ waitUntil: "domcontentloaded",+ });+ await expect(page.getByTestId("chat-input")).toBeVisible({+ timeout: 30_000,+ });++ // The local telemetry prompt can cover the conversation even when the+ // stored preference is seeded. Close it before measuring or capturing UI+ // evidence so the modal is neither part of the timing nor the screenshot.+ try {+ const consentForm = page.getByTestId("telemetry-consent-form");+ await consentForm.waitFor({ state: "visible", timeout: 5_000 });+ await consentForm+ .getByRole("button", { name: "Confirm preferences" })+ .click();+ await consentForm.waitFor({ state: "hidden", timeout: 5_000 });+ } catch {+ // The prompt is absent when the seeded consent has already synchronized.+ }++ const control = await runFixture(page, 5, 10);+ const longHistory = await runFixture(page, 20, 50);+ expect(control.codePreserved).toBe(true);+ expect(longHistory.codePreserved).toBe(true);+ expect(control.tokenSpans).toBeGreaterThanOrEqual(850);+ expect(longHistory.tokenSpans).toBeGreaterThanOrEqual(17_000);+ await expect(+ page.getByText("Final plain-text response.", { exact: true }),+ ).toBeVisible();+ await expect(page.getByText(/streaming-4/)).toBeVisible();++ measurements.push({+ context: contextIndex + 1,+ control,+ longHistory,+ });++ if (contextIndex === 0) {+ const conversationEvidence = page.getByTestId("chat-scroll-container");+ if (process.env.PERFORMANCE_SCREENSHOT_PATH) {+ await conversationEvidence.screenshot({+ path: process.env.PERFORMANCE_SCREENSHOT_PATH,+ });+ }+ await testInfo.attach("long-history-after.png", {+ body: await conversationEvidence.screenshot(),+ contentType: "image/png",+ });+ }+ await context.close();+ }++ const controlAppends = measurements.map(+ ({ control }) => control.append.composerLatencyMs,+ );+ const longAppends = measurements.map(+ ({ longHistory }) => longHistory.append.composerLatencyMs,+ );+ const controlStreaming = measurements.flatMap(({ control }) =>+ control.streaming.map(({ composerLatencyMs }) => composerLatencyMs),+ );+ const longStreaming = measurements.flatMap(({ longHistory }) =>+ longHistory.streaming.map(({ composerLatencyMs }) => composerLatencyMs),+ );+ const appendRatio = median(longAppends) / Math.max(median(controlAppends), 1);+ const streamingRatio =+ median(longStreaming) / Math.max(median(controlStreaming), 1);+ const longUpdateMaximum = Math.max(...longAppends, ...longStreaming);+ const longTaskMaximum = Math.max(+ 0,+ ...measurements.flatMap(({ longHistory }) => longHistory.longTasks),+ );++ const result = {+ measurements,+ summary: {+ controlAppendMedianMs: median(controlAppends),+ longAppendMedianMs: median(longAppends),+ appendRatio,+ controlStreamingMedianMs: median(controlStreaming),+ longStreamingMedianMs: median(longStreaming),+ streamingRatio,+ longUpdateMaximumMs: longUpdateMaximum,+ longTaskMaximumMs: longTaskMaximum,+ },+ };+ await testInfo.attach("performance-results.json", {+ body: Buffer.from(JSON.stringify(result, null, 2)),+ contentType: "application/json",+ });+ console.log("Issue #16910 performance results", JSON.stringify(result));++ expect(appendRatio).toBeLessThanOrEqual(2);+ expect(streamingRatio).toBeLessThanOrEqual(2);+ expect(longUpdateMaximum).toBeLessThanOrEqual(500);+ expect(longTaskMaximum).toBeLessThanOrEqual(500);+});