Skip to content

Commit 2ebaebd

Browse files
authored
fix(ui): re-attach chat transcript virtualizer after dashboard→split face switch (#123974)
* fix(ui): re-attach chat virtualizer when a foreign host re-stamps the transcript Switching a board session from Dashboard back to Split left the docked chat pane blank (sizer-height empty space, no rows) until an unrelated state change re-rendered the pane or the user scrolled. Root cause: the transcript template is stamped by openclaw-chat-sidebar-region (it receives the chat template as a property and renders it in its own, later update cycle), but the TanStack virtualizer only re-resolves its scroll element inside the pane host's update. After the face-switch re-stamp no pane update follows, so the virtualizer stayed detached: scrollElement null, scrollRect zeroed by the hide transition, calculateRange null, zero rows painted. Fix, at the owner (ChatSessionVirtualizerHost): attachment now follows the DOM identity the scroll-element ref records — an identity change queues a microtask that re-runs the virtualizer adapter's update hook. Zero-size rects from hide transitions (display:none sidebar panels, unmount teardown) are ignored so they can no longer wipe measured row heights or become the virtualizer viewport. Live-verified against a remote gateway where the broken state persisted 5+ seconds pre-fix and one attachment sync healed it. Regression tests fail pre-fix; e2e covers the deferred-latency dashboard->split flow. * chore(ui): raise startup JS baseline for transcript virtualizer re-attach fix Measured 333338 B gzip on PR #123974 run 31861214469 (+345 B over the base run 31860496921 at 332993 B; prior baseline 332040 B predates recent main drift). Absolute 350 KiB maintainer cap unchanged. Growth is the foreign-host attachment sync in chat-transcript-controller.ts — real fix code, not speculative surface.
1 parent aec8096 commit 2ebaebd

4 files changed

Lines changed: 259 additions & 4 deletions

File tree

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"startupJsGzipBytes": 333309,
3-
"reason": "cumulative 2026-08-15 UI fix growth (tab retry/session attention/talk backpressure stream); CI run 31861213699 build-artifacts bytes",
2+
"startupJsGzipBytes": 333338,
3+
"reason": "cumulative 2026-08-15 UI fix growth (tab retry/session attention/talk backpressure stream) plus chat transcript virtualizer re-attach fix (#123974); CI runs 31861213699 and 31861214469 build-artifacts bytes",
44
"updatedAt": "2026-08-15"
55
}
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
// Regression: the chat transcript must repaint after a dashboard -> split face
2+
// switch re-stamps it into the sidebar region (issue: virtualizer stayed
3+
// detached until an unrelated re-render, painting a blank pane).
4+
import { chromium, type Browser, type BrowserContext, type Page } from "playwright";
5+
import { afterAll, beforeAll, describe, expect, it } from "vitest";
6+
import {
7+
canRunPlaywrightChromium,
8+
controlUiBundledSettingsStorageKey,
9+
installMockGateway,
10+
resolvePlaywrightChromiumExecutablePath,
11+
startControlUiE2eServer,
12+
type ControlUiE2eServer,
13+
} from "../test-helpers/control-ui-e2e.ts";
14+
15+
const chromiumExecutablePath = resolvePlaywrightChromiumExecutablePath(chromium.executablePath());
16+
const chromiumAvailable = canRunPlaywrightChromium(chromiumExecutablePath);
17+
const allowMissingChromium = process.env.OPENCLAW_UI_E2E_ALLOW_MISSING_CHROMIUM === "1";
18+
const describeControlUiE2e = chromiumAvailable || !allowMissingChromium ? describe : describe.skip;
19+
const sessionKey = "agent:main:board-split-transcript";
20+
21+
let browser: Browser;
22+
let controlUi: ControlUiE2eServer;
23+
const contexts = new Set<BrowserContext>();
24+
25+
function boardSnapshot(chatDock: "right" | "hidden", revision = 1) {
26+
return {
27+
sessionKey,
28+
revision,
29+
tabs: [{ tabId: "main", title: "Main", position: 0, chatDock }],
30+
widgets: [],
31+
};
32+
}
33+
34+
async function visibleTranscriptState(page: Page) {
35+
return await page.evaluate(() => {
36+
const inner = [...document.querySelectorAll<HTMLElement>(".chat-thread-inner--virtual")].find(
37+
(candidate) => {
38+
const cachePane = candidate.closest(".chat-pane-cache__pane");
39+
return !cachePane || cachePane.classList.contains("chat-pane-cache__pane--visible");
40+
},
41+
);
42+
const scroller = inner?.parentElement;
43+
if (!inner || !scroller) {
44+
return { present: false, intersectingRows: 0 };
45+
}
46+
const rect = scroller.getBoundingClientRect();
47+
const intersectingRows = [...inner.querySelectorAll<HTMLElement>(".chat-virtual-row")].filter(
48+
(row) => {
49+
const rowRect = row.getBoundingClientRect();
50+
return rowRect.bottom > rect.top && rowRect.top < rect.bottom;
51+
},
52+
).length;
53+
return { present: true, intersectingRows };
54+
});
55+
}
56+
57+
describeControlUiE2e("Board split transcript restore", () => {
58+
beforeAll(async () => {
59+
controlUi = await startControlUiE2eServer();
60+
browser = await chromium.launch({ executablePath: chromiumExecutablePath });
61+
}, 120_000);
62+
63+
afterAll(async () => {
64+
for (const context of contexts) {
65+
await context.close();
66+
}
67+
await browser?.close();
68+
await controlUi?.close();
69+
});
70+
71+
it("repaints the docked transcript after dashboard -> split", async () => {
72+
const context = await browser.newContext({ viewport: { width: 1400, height: 900 } });
73+
contexts.add(context);
74+
const page = await context.newPage();
75+
const now = Date.now();
76+
const gateway = await installMockGateway(page, {
77+
sessionKey,
78+
featureMethods: [
79+
"board.get",
80+
"board.update",
81+
"chat.history",
82+
"chat.metadata",
83+
"chat.startup",
84+
"sessions.patch",
85+
],
86+
methodResponses: {
87+
"board.get": boardSnapshot("right"),
88+
"board.update": {
89+
sequence: [boardSnapshot("hidden", 2), boardSnapshot("right", 3)],
90+
},
91+
},
92+
historyMessages: Array.from({ length: 40 }, (_, index) => ({
93+
role: index % 2 === 0 ? "user" : "assistant",
94+
content: `Message number ${index}: the quick brown fox jumps over the lazy dog to give this bubble a realistic height.`,
95+
timestamp: now - (40 - index) * 60_000,
96+
})),
97+
});
98+
99+
const settingsKey = controlUiBundledSettingsStorageKey(controlUi.baseUrl);
100+
await page.addInitScript(
101+
({ key, storageKey }) => {
102+
const settings = JSON.parse(localStorage.getItem(storageKey) ?? "{}") as Record<
103+
string,
104+
unknown
105+
>;
106+
settings.boardSessionViews = { [key]: { activeTabId: "main" } };
107+
localStorage.setItem(storageKey, JSON.stringify(settings));
108+
},
109+
{ key: sessionKey, storageKey: settingsKey },
110+
);
111+
await page.goto(`${controlUi.baseUrl}dashboard`);
112+
await page.locator(".board-session-surface").waitFor();
113+
await page.getByText("Message number 39:").first().waitFor({ timeout: 15_000 });
114+
115+
const mode = (value: "split" | "dashboard") =>
116+
page.locator(`wa-radio.settings-segmented__btn[value="${value}"]`);
117+
118+
// Defer each dock update so the pane render that stamps the transcript into
119+
// the sidebar region arrives alone, as it does against a remote gateway.
120+
// With instant responses the click-time renders coalesce and mask the bug.
121+
await gateway.deferNext("board.update");
122+
await mode("dashboard").click();
123+
await page.waitForTimeout(200);
124+
await gateway.resolveDeferred("board.update");
125+
await expect
126+
.poll(async () => (await visibleTranscriptState(page)).present, { timeout: 5_000 })
127+
.toBe(false);
128+
129+
await gateway.deferNext("board.update");
130+
await mode("split").click();
131+
await page.waitForTimeout(200);
132+
await gateway.resolveDeferred("board.update");
133+
134+
// The transcript must repaint promptly from the dock-restore render itself,
135+
// without waiting for an unrelated state change to re-render the pane.
136+
await expect
137+
.poll(async () => await visibleTranscriptState(page), { timeout: 2_000 })
138+
.toMatchObject({ present: true, intersectingRows: expect.any(Number) });
139+
await expect
140+
.poll(async () => (await visibleTranscriptState(page)).intersectingRows, { timeout: 2_000 })
141+
.toBeGreaterThan(0);
142+
await page
143+
.getByText("Message number 39:")
144+
.first()
145+
.waitFor({ state: "visible", timeout: 2_000 });
146+
}, 120_000);
147+
});

‎ui/src/pages/chat/components/chat-transcript-controller.test.ts‎

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/* @vitest-environment jsdom */
22

3-
import { render } from "lit";
3+
import { nothing, render } from "lit";
44
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
55
import { createTestTranscript } from "../chat-view.test-helpers.ts";
66
import { renderChatThread } from "./chat-thread.ts";
@@ -131,6 +131,14 @@ describe("chat transcript controller", () => {
131131

132132
const scrollElement = container.querySelector<HTMLElement>(".chat-thread");
133133
expect(scrollElement).not.toBeNull();
134+
// Establish the real viewport baseline first: zero rects from jsdom's
135+
// 0-width offsetWidth are ignored as hide transitions, matching browsers
136+
// where the initial attach rect is the true width.
137+
for (const observer of resizeObservers) {
138+
if (observer.observes(scrollElement!)) {
139+
observer.emit(800, 600);
140+
}
141+
}
134142
scrollElement!.scrollTop = 40;
135143
scrollElement!.dispatchEvent(new Event("scroll"));
136144
const virtualizer = (
@@ -215,4 +223,68 @@ describe("chat transcript controller", () => {
215223
transcript.hostDisconnected();
216224
},
217225
);
226+
227+
it("re-attaches the virtualizer when a foreign host re-stamps the transcript", async () => {
228+
const transcript = createTestTranscript();
229+
const props = threadProps("pane-foreign-stamp");
230+
const chatFace = document.body.appendChild(document.createElement("div"));
231+
render(renderChatThread(props, transcript), chatFace);
232+
transcript.hostConnected();
233+
transcript.hostUpdated();
234+
await flushDeferredRowPrune();
235+
const chatScroller = chatFace.querySelector<HTMLElement>(".chat-thread");
236+
expect(chatScroller).not.toBeNull();
237+
expect(observedElements.has(chatScroller!)).toBe(true);
238+
239+
// Dashboard face: the pane unmounts the transcript and finishes its update.
240+
render(nothing, chatFace);
241+
transcript.hostUpdated();
242+
await flushDeferredRowPrune();
243+
244+
// Split restore: the sidebar region — a different Lit host that receives
245+
// the chat template as a property — stamps the transcript in its own
246+
// update cycle. The pane does not update again, so attachment must follow
247+
// the ref-recorded DOM identity rather than the pane's render cycle.
248+
const dock = document.body.appendChild(document.createElement("div"));
249+
render(renderChatThread(props, transcript), dock);
250+
await flushDeferredRowPrune();
251+
252+
const dockScroller = dock.querySelector<HTMLElement>(".chat-thread");
253+
expect(dockScroller).not.toBeNull();
254+
expect(observedElements.has(dockScroller!)).toBe(true);
255+
expect(transcriptRows(dock).length).toBeGreaterThan(0);
256+
transcript.hostDisconnected();
257+
});
258+
259+
it("keeps rendering rows after a hide-transition zero rect", async () => {
260+
const transcript = createTestTranscript();
261+
const container = document.body.appendChild(document.createElement("div"));
262+
const messages = Array.from({ length: 40 }, (_, index) => ({
263+
role: index % 2 === 0 ? "user" : "assistant",
264+
content: `message ${index}`,
265+
timestamp: index + 1,
266+
}));
267+
const props = threadProps("pane-zero-rect", "agent:main:zero-rect", messages);
268+
render(renderChatThread(props, transcript), container);
269+
transcript.hostConnected();
270+
transcript.hostUpdated();
271+
await flushDeferredRowPrune();
272+
const scrollElement = container.querySelector<HTMLElement>(".chat-thread");
273+
expect(scrollElement).not.toBeNull();
274+
expect(transcriptRows(container).length).toBeGreaterThan(0);
275+
276+
// A pane cache or face switch hiding the transcript reports a 0x0 rect.
277+
// It must not become the virtualizer's viewport (an empty range renders a
278+
// blank transcript) nor count as a width change that wipes measurements.
279+
for (const observer of resizeObservers) {
280+
if (observer.observes(scrollElement!)) {
281+
observer.emit(0, 0);
282+
}
283+
}
284+
render(renderChatThread(props, transcript), container);
285+
transcript.hostUpdated();
286+
287+
expect(transcriptRows(container).length).toBeGreaterThan(0);
288+
transcript.hostDisconnected();
289+
});
218290
});

‎ui/src/pages/chat/components/chat-transcript-controller.ts‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,36 @@ class ChatSessionVirtualizerHost implements ReactiveControllerHost, ChatTranscri
101101
// re-invoke them for every visible row and re-measure each row every render.
102102
// Lit tracks the last element per callback, so each row needs its own.
103103
private readonly scrollElementRef = (element?: Element) => {
104-
this.threadInnerElement = element instanceof HTMLDivElement ? element : null;
104+
const next = element instanceof HTMLDivElement ? element : null;
105+
if (next === this.threadInnerElement) {
106+
return;
107+
}
108+
this.threadInnerElement = next;
109+
this.queueScrollElementAttach();
105110
};
111+
// The transcript template can be stamped by a host other than the pane that
112+
// drives this controller: sidebar panels receive it as a property and render
113+
// it in their own, later update cycle. The virtualizer re-resolves its
114+
// scroll element only inside _willUpdate, which runs on the pane's update —
115+
// after a foreign-host re-stamp (chat<->dashboard face switch docking chat
116+
// into the sidebar) no pane update follows, so the virtualizer stays
117+
// detached and paints zero rows until an unrelated re-render. Attachment
118+
// must follow the DOM identity this ref records, not the pane render cycle.
119+
private scrollElementAttachQueued = false;
120+
private queueScrollElementAttach(): void {
121+
if (this.scrollElementAttachQueued) {
122+
return;
123+
}
124+
this.scrollElementAttachQueued = true;
125+
queueMicrotask(() => {
126+
this.scrollElementAttachQueued = false;
127+
const instance = this.virtualizerController.getVirtualizer();
128+
if (this.connected && instance.scrollElement !== this.scrollElement) {
129+
this.virtualizerController.hostUpdated();
130+
this.host.requestUpdate();
131+
}
132+
});
133+
}
106134
private readonly measureRowRefs = new Map<string, (element?: Element) => void>();
107135
private pruneDetachedRowsQueued = false;
108136
private pendingRowMeasureFrame: number | null = null;
@@ -195,6 +223,14 @@ class ChatSessionVirtualizerHost implements ReactiveControllerHost, ChatTranscri
195223
followOnAppend: false,
196224
observeElementRect: (instance, callback) =>
197225
observeElementRect(instance, (rect) => {
226+
// A zero rect is a hide/teardown transition (pane cache display:none
227+
// or a face switch unmounting the transcript), not a real resize.
228+
// Reacting to it wipes every measured row height via measure() and
229+
// records garbage as the last width/height; keep the last real rect
230+
// so a remount with unchanged geometry restores rows instantly.
231+
if (rect.width === 0 || rect.height === 0) {
232+
return;
233+
}
198234
const previousHeight = this.observedHeight;
199235
const widthChanged = this.observedWidth !== null && this.observedWidth !== rect.width;
200236
const heightChanged = previousHeight !== null && previousHeight !== rect.height;

0 commit comments

Comments
 (0)