Skip to content

Commit 0e49684

Browse files
fix(ui): remeasure chat rows after panel resize (#117687)
* fix(ui): remeasure chat rows after panel resize * test(ui): satisfy panel reflow lint * test(ui): cover panel resize while scrolling * fix(ui): preserve virtualizer scroll ownership
1 parent d976f88 commit 0e49684

3 files changed

Lines changed: 264 additions & 7 deletions

File tree

Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
import { mkdir, rm } from "node:fs/promises";
2+
import path from "node:path";
3+
import { chromium, type Browser } from "playwright";
4+
import { afterAll, beforeAll, describe, expect, it } from "vitest";
5+
import {
6+
canRunPlaywrightChromium,
7+
installMockGateway,
8+
resolvePlaywrightChromiumExecutablePath,
9+
startControlUiE2eServer,
10+
type ControlUiE2eServer,
11+
} from "../test-helpers/control-ui-e2e.ts";
12+
13+
const chromiumExecutablePath = resolvePlaywrightChromiumExecutablePath(chromium.executablePath());
14+
const chromiumAvailable = canRunPlaywrightChromium(chromiumExecutablePath);
15+
const allowMissingChromium = process.env.OPENCLAW_UI_E2E_ALLOW_MISSING_CHROMIUM === "1";
16+
const describeControlUiE2e = chromiumAvailable || !allowMissingChromium ? describe : describe.skip;
17+
const artifactDir = path.resolve(process.cwd(), ".artifacts/control-ui-e2e/chat-panel-reflow");
18+
const chatSessionKey = "agent:main:main";
19+
20+
const longReply =
21+
"Additional runtime work may make an earlier benchmark misleading. " +
22+
"The current implementation must preserve the visible conversation while panels resize the transcript. ";
23+
24+
const historyMessageCount = 4;
25+
const historyMessages = Array.from({ length: historyMessageCount }, (_, index) => ({
26+
id: `message-${index}`,
27+
role: index % 2 === 0 ? "user" : "assistant",
28+
content: [
29+
{
30+
type: "text",
31+
text: `${index + 1}. ${longReply.repeat(3)}\n\n${longReply.repeat(2)}`,
32+
},
33+
],
34+
timestamp: Date.now() - (historyMessageCount - index) * 1_000,
35+
}));
36+
37+
async function expectMessagesNotToOverlap(page: import("playwright").Page): Promise<void> {
38+
await expect
39+
.poll(() =>
40+
page.locator(".chat-group").evaluateAll((groups) => {
41+
const visible = groups
42+
.map((group, index) => {
43+
const rect = group.getBoundingClientRect();
44+
return { bottom: rect.bottom, index, top: rect.top };
45+
})
46+
.filter((rect) => rect.bottom > 0 && rect.top < window.innerHeight)
47+
.toSorted((a, b) => a.top - b.top);
48+
return visible.slice(1).flatMap((current, index) => {
49+
const previous = visible[index];
50+
if (!previous || current.top >= previous.bottom - 1) {
51+
return [];
52+
}
53+
return [
54+
{
55+
current: current.index,
56+
overlap: previous.bottom - current.top,
57+
previous: previous.index,
58+
},
59+
];
60+
});
61+
}),
62+
)
63+
.toEqual([]);
64+
}
65+
66+
let server: ControlUiE2eServer;
67+
let browser: Browser;
68+
69+
describeControlUiE2e("chat transcript panel reflow", () => {
70+
beforeAll(async () => {
71+
if (!chromiumAvailable) {
72+
throw new Error(`Playwright Chromium is unavailable at ${chromiumExecutablePath}`);
73+
}
74+
server = await startControlUiE2eServer();
75+
browser = await chromium.launch({ executablePath: chromiumExecutablePath });
76+
});
77+
78+
afterAll(async () => {
79+
await browser?.close();
80+
await server?.close();
81+
});
82+
83+
it("keeps transcript rows separate across background-task, file, and diff panel toggles", async () => {
84+
await rm(artifactDir, { force: true, recursive: true });
85+
await mkdir(artifactDir, { recursive: true });
86+
const context = await browser.newContext({
87+
locale: "en-US",
88+
serviceWorkers: "block",
89+
viewport: { height: 900, width: 1280 },
90+
});
91+
const page = await context.newPage();
92+
try {
93+
await installMockGateway(page, {
94+
featureMethods: ["chat.metadata", "chat.startup", "sessions.diff"],
95+
historyMessages,
96+
methodResponses: {
97+
"artifacts.list": { artifacts: [] },
98+
"sessions.diff": {
99+
additions: 1,
100+
baseRef: "main",
101+
branch: "feature/reflow",
102+
deletions: 0,
103+
files: [
104+
{
105+
additions: 1,
106+
deletions: 0,
107+
patch: [
108+
"diff --git a/src/app.ts b/src/app.ts",
109+
"--- a/src/app.ts",
110+
"+++ b/src/app.ts",
111+
"@@ -1 +1,2 @@",
112+
" current line",
113+
"+new line",
114+
"",
115+
].join("\n"),
116+
path: "src/app.ts",
117+
status: "modified",
118+
},
119+
],
120+
root: "/workspace",
121+
sessionKey: "main",
122+
},
123+
"sessions.files.list": {
124+
browser: { entries: [], path: "" },
125+
files: [
126+
{
127+
kind: "modified",
128+
missing: false,
129+
name: "AGENTS.md",
130+
path: "/workspace/AGENTS.md",
131+
size: 2048,
132+
},
133+
],
134+
root: "/workspace",
135+
sessionKey: "main",
136+
},
137+
"tasks.list": {
138+
tasks: [
139+
{
140+
agentId: "main",
141+
createdAt: Date.now() - 5_000,
142+
id: "task-reflow",
143+
kind: "subagent",
144+
ownerKey: chatSessionKey,
145+
progressSummary: "Checking transcript layout",
146+
runtime: "subagent",
147+
startedAt: Date.now() - 4_000,
148+
status: "running",
149+
taskId: "task-reflow",
150+
title: "Reflow proof",
151+
updatedAt: Date.now(),
152+
},
153+
],
154+
},
155+
},
156+
});
157+
158+
const response = await page.goto(`${server.baseUrl}chat`);
159+
expect(response?.status()).toBe(200);
160+
await expect.poll(() => page.locator(".chat-group").count()).toBe(historyMessageCount);
161+
await page.locator(".chat-thread").evaluate((element) => {
162+
element.scrollTop = Math.max(0, element.scrollHeight / 2);
163+
});
164+
await expectMessagesNotToOverlap(page);
165+
await page.screenshot({ path: path.join(artifactDir, "00-closed.png") });
166+
167+
await page.getByRole("button", { name: "Show background tasks" }).click();
168+
await page.locator(".chat-tasks-rail").waitFor({ state: "visible" });
169+
await expectMessagesNotToOverlap(page);
170+
await page.screenshot({ path: path.join(artifactDir, "01-background-tasks.png") });
171+
172+
await page.getByRole("button", { name: "Show thread files", exact: true }).click();
173+
await page.locator(".chat-workspace-rail").waitFor({ state: "visible" });
174+
await expectMessagesNotToOverlap(page);
175+
await page.screenshot({ path: path.join(artifactDir, "02-thread-files.png") });
176+
177+
await page.locator(".chat-session-diff-toggle").first().click();
178+
await page.locator(".session-diff").waitFor({ state: "visible" });
179+
await expectMessagesNotToOverlap(page);
180+
await page.screenshot({ path: path.join(artifactDir, "03-thread-changes.png") });
181+
} finally {
182+
await context.close();
183+
}
184+
});
185+
});

‎ui/src/pages/chat/components/chat-thread.measure.test.ts‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626

2727
const observedElements = new Set<Element>();
2828
const resizeObservers = new Set<RecordingResizeObserver>();
29+
let measuredRowHeight = 100;
2930

3031
class RecordingResizeObserver implements ResizeObserver {
3132
private readonly targets = new Set<Element>();
@@ -59,6 +60,10 @@ class RecordingResizeObserver implements ResizeObserver {
5960
this.callback(entries, this);
6061
}
6162
}
63+
64+
observes(target: Element): boolean {
65+
return this.targets.has(target);
66+
}
6267
}
6368

6469
const defaultMessages = [
@@ -107,11 +112,14 @@ describe("chat transcript row measurement", () => {
107112
beforeEach(() => {
108113
observedElements.clear();
109114
resizeObservers.clear();
115+
measuredRowHeight = 100;
110116
vi.stubGlobal("ResizeObserver", RecordingResizeObserver);
111117
// jsdom reports 0x0 rects and offsetHeight 0; keep the virtualizer
112118
// viewport and measured row sizes non-zero so re-renders keep producing
113119
// virtual rows.
114-
vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(100);
120+
vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockImplementation(
121+
() => measuredRowHeight,
122+
);
115123
vi.spyOn(Element.prototype, "getBoundingClientRect").mockReturnValue({
116124
x: 0,
117125
y: 0,
@@ -357,6 +365,46 @@ describe("chat transcript row measurement", () => {
357365
expect(observedElements.size).toBe(0);
358366
});
359367

368+
it("updates rendered row offsets from freshly wrapped heights while scrolling", async () => {
369+
const transcript = createTestTranscript();
370+
const container = document.body.appendChild(document.createElement("div"));
371+
const props = threadProps("pane-width-remeasure");
372+
const renderTranscript = async () => {
373+
render(renderChatThread(props, transcript), container);
374+
transcript.hostUpdated();
375+
await flushDeferredRowPrune();
376+
};
377+
378+
await renderTranscript();
379+
transcript.hostConnected();
380+
await renderTranscript();
381+
expect(transcriptRows(container)[1]?.style.transform).toBe("translateY(100px)");
382+
383+
const scrollElement = container.querySelector<HTMLElement>(".chat-thread");
384+
expect(scrollElement).not.toBeNull();
385+
scrollElement!.scrollTop = 40;
386+
scrollElement!.dispatchEvent(new Event("scroll"));
387+
const virtualizer = (
388+
transcript as unknown as {
389+
sessionVirtualizer: {
390+
virtualizerController: { getVirtualizer: () => { isScrolling: boolean } };
391+
};
392+
}
393+
).sessionVirtualizer.virtualizerController.getVirtualizer();
394+
expect(virtualizer.isScrolling).toBe(true);
395+
396+
measuredRowHeight = 180;
397+
for (const observer of resizeObservers) {
398+
if (scrollElement && observer.observes(scrollElement)) {
399+
observer.emit(640, 600);
400+
}
401+
}
402+
await renderTranscript();
403+
404+
expect(transcriptRows(container)[1]?.style.transform).toBe("translateY(180px)");
405+
transcript.hostDisconnected();
406+
});
407+
360408
it("rebinds guarded transcript images when the gateway rotates its auth token", async () => {
361409
const NativeUrl = URL;
362410
const blobUrl = `blob:transcript-media-${crypto.randomUUID()}`;

‎ui/src/pages/chat/components/chat-thread.ts‎

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,28 @@ class ChatSessionVirtualizerHost implements ReactiveControllerHost {
264264
};
265265
private readonly measureRowRefs = new Map<string, (element?: Element) => void>();
266266
private pruneDetachedRowsQueued = false;
267+
private pendingRowMeasureFrame: number | null = null;
268+
private measureConnectedRows(): void {
269+
// Only width invalidation owns forced DOM reads. Ordinary row refs stay on
270+
// TanStack's observer path so resizeItem cannot perturb scroll restoration.
271+
const instance = this.virtualizerController.getVirtualizer();
272+
for (const row of this.threadInnerElement?.querySelectorAll<HTMLElement>(".chat-virtual-row") ??
273+
[]) {
274+
instance.resizeItem(
275+
instance.indexFromElement(row),
276+
row[instance.options.horizontal ? "offsetWidth" : "offsetHeight"],
277+
);
278+
}
279+
}
280+
private queueConnectedRowMeasure(): void {
281+
if (this.pendingRowMeasureFrame !== null) {
282+
return;
283+
}
284+
this.pendingRowMeasureFrame = requestAnimationFrame(() => {
285+
this.pendingRowMeasureFrame = null;
286+
this.measureConnectedRows();
287+
});
288+
}
267289
private measureRowRefFor(key: string): (element?: Element) => void {
268290
let callback = this.measureRowRefs.get(key);
269291
if (!callback) {
@@ -322,13 +344,11 @@ class ChatSessionVirtualizerHost implements ReactiveControllerHost {
322344
callback(rect);
323345
if (widthChanged) {
324346
// Cached offscreen sizes belong to the old wrapping width. Reset
325-
// them and synchronously seed connected rows to avoid stale overlap.
347+
// them, seed current rows, then repeat after any same-commit
348+
// re-stamp has attached and completed layout.
326349
instance.measure();
327-
for (const row of this.threadInnerElement?.querySelectorAll<HTMLElement>(
328-
".chat-virtual-row",
329-
) ?? []) {
330-
instance.measureElement(row);
331-
}
350+
this.measureConnectedRows();
351+
this.queueConnectedRowMeasure();
332352
}
333353
}),
334354
rangeExtractor: (range) => {
@@ -399,6 +419,10 @@ class ChatSessionVirtualizerHost implements ReactiveControllerHost {
399419
}
400420

401421
disconnect(): void {
422+
if (this.pendingRowMeasureFrame !== null) {
423+
cancelAnimationFrame(this.pendingRowMeasureFrame);
424+
this.pendingRowMeasureFrame = null;
425+
}
402426
if (this.pendingScrollFrame !== null) {
403427
cancelAnimationFrame(this.pendingScrollFrame);
404428
this.pendingScrollFrame = null;

0 commit comments

Comments
 (0)