Skip to content

Commit 0598c00

Browse files
committed
perf(ui): keep chat render state alive across session switches
Retain bounded per-session chat items and virtualizer measurements, avoid redundant tool-card walks, and reduce markdown cache churn during rapid switching. User-visible behavior: switching back to a session now restores its prior reading position while end-anchored sessions continue following the latest message.
1 parent a5ee503 commit 0598c00

15 files changed

Lines changed: 1036 additions & 36 deletions

‎ui/src/components/markdown.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,9 @@ const sanitizeOptions = {
8686
let hooksInstalled = false;
8787
const MARKDOWN_CHAR_LIMIT = 140_000;
8888
const MARKDOWN_PARSE_LIMIT = 40_000;
89-
const MARKDOWN_CACHE_LIMIT = 200;
89+
// Covers several message-heavy sessions during rapid switching. Only inputs
90+
// up to 50k characters enter this 500-entry LRU, keeping memory bounded.
91+
const MARKDOWN_CACHE_LIMIT = 500;
9092
const MARKDOWN_CACHE_MAX_CHARS = 50_000;
9193
const DOCS_ORIGIN = "https://docs.openclaw.ai";
9294
const DOCS_ROOT_SEGMENTS = new Set([

‎ui/src/e2e/chat-flow.history-recovery.e2e.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,9 @@ suite.define(() => {
306306
});
307307

308308
await sessionB.click();
309-
await page.getByText(/^recent retained message 140\n/).waitFor({ timeout: 10_000 });
309+
// Returning preserves the reading position at the loaded-history start;
310+
// the user can still use the normal jump-to-end control for message 140.
311+
await page.getByText(/^older retained message 1\n/).waitFor({ timeout: 10_000 });
310312
await new Promise<void>((resolve) => {
311313
setTimeout(resolve, 800);
312314
});

‎ui/src/e2e/chat-flow.navigation-presentation.e2e.test.ts‎

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,128 @@ import {
99
installMockGateway,
1010
requireRecord,
1111
sidebarSessionOrder,
12+
waitForChatScrollIdle,
1213
} from "./chat-flow.test-support.ts";
1314

1415
const suite = createChatFlowE2eSuite();
1516

1617
suite.define(() => {
18+
it("restores a scrolled session after switching away while new messages arrive", async () => {
19+
const context = await suite.newBrowserContext({
20+
locale: "en-US",
21+
serviceWorkers: "block",
22+
viewport: { height: 720, width: 1280 },
23+
});
24+
const page = await context.newPage();
25+
const sessionA = "agent:main:session-a";
26+
const sessionB = "agent:main:session-b";
27+
const messages = (label: string, count: number) =>
28+
Array.from({ length: count }, (_, index) => ({
29+
role: index % 2 === 0 ? "user" : "assistant",
30+
content: `${label} message ${index}: ${"wrapped transcript content ".repeat(8)}`,
31+
timestamp: 1_000 + index,
32+
__openclaw: { seq: index + 1 },
33+
}));
34+
const response = (sessionKey: string, transcript: unknown[]) => ({
35+
messages: transcript,
36+
sessionId: `${sessionKey}:backing`,
37+
thinkingLevel: null,
38+
});
39+
const responseCases = (messagesA: unknown[], messagesB = messages("B", 30)) => ({
40+
cases: [
41+
{ match: { sessionKey: sessionA }, response: response(sessionA, messagesA) },
42+
{ match: { sessionKey: sessionB }, response: response(sessionB, messagesB) },
43+
],
44+
});
45+
const initialMessagesA = messages("A", 70);
46+
const initialResponses = responseCases(initialMessagesA);
47+
const gateway = await installMockGateway(page, {
48+
methodResponses: {
49+
"chat.history": initialResponses,
50+
"chat.startup": initialResponses,
51+
"sessions.list": chatSessionListResponse(),
52+
},
53+
sessionKey: sessionA,
54+
});
55+
56+
try {
57+
await page.goto(`${suite.server.baseUrl}chat`);
58+
await waitForChatScrollIdle(page);
59+
const thread = page.locator(".chat-thread");
60+
await expect.poll(() => thread.count()).toBe(1);
61+
const initialDistance = await thread.evaluate((element) => {
62+
const transcript = element as HTMLElement;
63+
return transcript.scrollHeight - transcript.scrollTop - transcript.clientHeight;
64+
});
65+
expect(initialDistance).toBeLessThanOrEqual(8);
66+
const storedScrollTop = await thread.evaluate((element) => {
67+
const transcript = element as HTMLElement;
68+
transcript.scrollTop = Math.floor((transcript.scrollHeight - transcript.clientHeight) / 3);
69+
transcript.dispatchEvent(new Event("scroll", { bubbles: true }));
70+
return transcript.scrollTop;
71+
});
72+
expect(storedScrollTop).toBeGreaterThan(0);
73+
74+
const sessionLink = (sessionKey: string) =>
75+
page.locator(
76+
`.sidebar-recent-session[data-session-key="${sessionKey}"] a.sidebar-recent-session__link`,
77+
);
78+
await sessionLink(sessionB).click();
79+
await expect.poll(() => new URL(page.url()).pathname).toBe(controlUiSessionPath(sessionB));
80+
await waitForChatScrollIdle(page);
81+
const firstVisitDistance = await thread.evaluate((element) => {
82+
const transcript = element as HTMLElement;
83+
return transcript.scrollHeight - transcript.scrollTop - transcript.clientHeight;
84+
});
85+
expect(firstVisitDistance).toBeLessThanOrEqual(8);
86+
87+
const messagesAWithNewTail = messages("A", 78);
88+
const updatedResponses = responseCases(messagesAWithNewTail);
89+
await gateway.setMethodResponse("chat.history", updatedResponses);
90+
await gateway.setMethodResponse("chat.startup", updatedResponses);
91+
const historyRequestsBeforeReturn = (await gateway.getRequests("chat.history")).length;
92+
await sessionLink(sessionA).click();
93+
await expect.poll(() => new URL(page.url()).pathname).toBe(controlUiSessionPath(sessionA));
94+
await expect
95+
.poll(async () => (await gateway.getRequests("chat.history")).length)
96+
.toBeGreaterThan(historyRequestsBeforeReturn);
97+
await waitForChatScrollIdle(page);
98+
99+
const restored = await thread.evaluate((element) => {
100+
const transcript = element as HTMLElement;
101+
return {
102+
distanceFromBottom:
103+
transcript.scrollHeight - transcript.scrollTop - transcript.clientHeight,
104+
scrollTop: transcript.scrollTop,
105+
};
106+
});
107+
expect(
108+
Math.abs(restored.scrollTop - storedScrollTop),
109+
JSON.stringify({ restored, storedScrollTop }),
110+
).toBeLessThanOrEqual(120);
111+
expect(restored.distanceFromBottom).toBeGreaterThan(8);
112+
113+
const messagesBWithNewTail = messages("B", 36);
114+
const endAnchoredResponses = responseCases(messagesAWithNewTail, messagesBWithNewTail);
115+
await gateway.setMethodResponse("chat.history", endAnchoredResponses);
116+
await gateway.setMethodResponse("chat.startup", endAnchoredResponses);
117+
const historyRequestsBeforeEndReturn = (await gateway.getRequests("chat.history")).length;
118+
await sessionLink(sessionB).click();
119+
await expect.poll(() => new URL(page.url()).pathname).toBe(controlUiSessionPath(sessionB));
120+
await expect
121+
.poll(async () => (await gateway.getRequests("chat.history")).length)
122+
.toBeGreaterThan(historyRequestsBeforeEndReturn);
123+
await waitForChatScrollIdle(page);
124+
const endAnchoredDistance = await thread.evaluate((element) => {
125+
const transcript = element as HTMLElement;
126+
return transcript.scrollHeight - transcript.scrollTop - transcript.clientHeight;
127+
});
128+
expect(endAnchoredDistance).toBeLessThanOrEqual(8);
129+
} finally {
130+
await suite.closeBrowserContext(context);
131+
}
132+
});
133+
17134
it("renders always-on pane headers without desktop topbar chrome", async () => {
18135
const context = await suite.newBrowserContext({
19136
locale: "en-US",

‎ui/src/pages/chat/chat-pane-base.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import {
3232
type ChatHistoryPagination,
3333
type ChatMessageCache,
3434
type ChatPageHost,
35+
type ChatSessionScrollPosition,
3536
type ChatPaneHeaderAction,
3637
type ChatSessionSharingState,
3738
type ControlUiSessionBranch,
@@ -362,6 +363,9 @@ export abstract class ChatPaneBase extends OpenClawLightDomElement {
362363
protected abstract applyApplicationConfig(config: ChatPageContext["config"]["current"]): void;
363364
protected abstract applySessionsState(state: ChatPageContext["sessions"]["state"]): void;
364365
protected abstract cancelHeaderRename(): void;
365-
protected abstract resetOlderMessagesViewport(): void;
366+
protected abstract resetOlderMessagesViewport(
367+
nextSessionKey?: string,
368+
): ChatSessionScrollPosition | null;
369+
protected abstract restoreOlderMessagesViewport(sessionKey: string, scrollTop: number): void;
366370
protected abstract sendPendingSkillWorkshopRevision(expectedSessionKey: string): void;
367371
}

‎ui/src/pages/chat/chat-pane-deps.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,7 @@ export type { SessionDiscussionPanelConfig } from "./components/session-discussi
273273
export {
274274
ChatTranscriptController,
275275
resetChatThreadPresentationState,
276+
resetChatThreadSessionPresentationState,
276277
} from "./components/chat-thread.ts";
277278
export { WIDGET_PROMPT_EVENT, type WidgetPromptEventDetail } from "./components/chat-tool-cards.ts";
278279
export {
@@ -289,7 +290,14 @@ export {
289290
reconcileStaleChatRunAfterSessionStatePublication,
290291
replayPendingChatAbort,
291292
} from "./run-lifecycle.ts";
292-
export { scheduleChatScroll } from "./scroll.ts";
293+
export {
294+
captureChatSessionScrollPosition,
295+
getChatSessionScrollPosition,
296+
restoreChatScroll,
297+
saveChatSessionScrollPosition,
298+
scheduleChatScroll,
299+
type ChatSessionScrollPosition,
300+
} from "./scroll.ts";
293301
export {
294302
clearChatMessagesFromCache,
295303
readChatSessionSnapshot,

‎ui/src/pages/chat/chat-pane-history.test.ts‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ import type { SessionCapability } from "../../lib/sessions/index.ts";
1313
import "./chat-pane.ts";
1414
import { loadChatHistory } from "./chat-history.ts";
1515
import type { ChatPageHost } from "./chat-state-host.ts";
16+
import type { AfterCommitEffect } from "./render-lifecycle.ts";
17+
import type { ChatSessionScrollPosition } from "./scroll.ts";
1618

1719
type TestChatPane = HTMLElement & {
1820
catalogMessages: unknown[];
@@ -37,6 +39,13 @@ type TestChatPane = HTMLElement & {
3739
hasOlderMessages: () => boolean;
3840
loadingOlder: boolean;
3941
olderOffsetsSeen: Set<number>;
42+
resetOlderMessagesViewport: (nextSessionKey?: string) => ChatSessionScrollPosition | null;
43+
restoreOlderMessagesViewport: (sessionKey: string, scrollTop: number) => void;
44+
transcriptScrollTop: number | null;
45+
transcript: {
46+
activeSessionKey: string | null;
47+
pendingScrollOffsetFor: (sessionKey: string) => number | null;
48+
};
4049
};
4150

4251
function createDeferred<T>() {
@@ -99,6 +108,16 @@ function createTestChatPane(params: { client: GatewayBrowserClient; sessions: Se
99108
sidebarLayout: { columns: [] },
100109
chatScrollGeneration: 0,
101110
chatScrollCommitCleanup: null,
111+
chatScrollFrame: null,
112+
chatScrollGuardFrame: null,
113+
chatLastScrollTop: 0,
114+
chatLastScrollHeight: 0,
115+
chatHasAutoScrolled: false,
116+
chatUserNearBottom: true,
117+
chatFollowLocked: false,
118+
chatNewMessagesBelow: false,
119+
chatIsProgrammaticScroll: false,
120+
chatProgrammaticScrollTarget: 0,
102121
handleChatScroll: vi.fn(),
103122
renderLifecycle: { afterCommit: () => () => {}, invalidate: () => {} },
104123
} as unknown as ChatPageHost;
@@ -158,6 +177,83 @@ function nativeHistorySeq(message: unknown): number | undefined {
158177
}
159178

160179
describe("chat pane native history pagination", () => {
180+
it("restores a saved per-session viewport while first visits keep the end anchor", () => {
181+
const client = { request: vi.fn() } as unknown as GatewayBrowserClient;
182+
const { pane, state } = createTestChatPane({ client, sessions: {} as SessionCapability });
183+
const thread = document.createElement("div");
184+
thread.className = "chat-thread";
185+
Object.defineProperty(thread, "scrollHeight", { configurable: true, value: 2_600 });
186+
Object.defineProperty(thread, "clientHeight", { configurable: true, value: 500 });
187+
thread.scrollTop = 420;
188+
pane.append(thread);
189+
pane.transcript.activeSessionKey = state.sessionKey;
190+
191+
expect(pane.resetOlderMessagesViewport("agent:main:session-b")).toBeNull();
192+
state.sessionKey = "agent:main:session-b";
193+
pane.transcript.activeSessionKey = state.sessionKey;
194+
thread.scrollTop = 80;
195+
expect(pane.resetOlderMessagesViewport("agent:main:current")).toEqual({
196+
scrollTop: 420,
197+
anchorToEnd: false,
198+
});
199+
200+
state.sessionKey = "agent:main:current";
201+
pane.transcript.activeSessionKey = state.sessionKey;
202+
let commitEffect: AfterCommitEffect | undefined;
203+
state.renderLifecycle.afterCommit = vi.fn((effect: AfterCommitEffect) => {
204+
commitEffect = effect;
205+
return vi.fn();
206+
});
207+
pane.restoreOlderMessagesViewport(state.sessionKey, 420);
208+
commitEffect?.(vi.fn());
209+
210+
expect(thread.scrollTop).toBe(420);
211+
expect(pane.transcriptScrollTop).toBe(420);
212+
expect(state.chatHasAutoScrolled).toBe(true);
213+
expect(state.chatFollowLocked).toBe(true);
214+
expect(state.chatNewMessagesBelow).toBe(true);
215+
216+
// A rapid second switch sees a transient DOM top of zero while the
217+
// logical restore is still pending; it must retain the logical 420px.
218+
thread.scrollTop = 0;
219+
const pendingScrollOffset = vi
220+
.spyOn(pane.transcript, "pendingScrollOffsetFor")
221+
.mockReturnValue(420);
222+
expect(pane.resetOlderMessagesViewport("agent:main:session-b")).toEqual({
223+
scrollTop: 80,
224+
anchorToEnd: false,
225+
});
226+
pendingScrollOffset.mockRestore();
227+
state.sessionKey = "agent:main:session-b";
228+
pane.transcript.activeSessionKey = state.sessionKey;
229+
expect(pane.resetOlderMessagesViewport("agent:main:current")).toEqual({
230+
scrollTop: 420,
231+
anchorToEnd: false,
232+
});
233+
});
234+
235+
it("restores through equivalent default-main session keys", () => {
236+
const client = { request: vi.fn() } as unknown as GatewayBrowserClient;
237+
const { pane, state } = createTestChatPane({ client, sessions: {} as SessionCapability });
238+
state.sessionKey = "agent:main:main";
239+
const thread = document.createElement("div");
240+
thread.className = "chat-thread";
241+
Object.defineProperty(thread, "scrollHeight", { configurable: true, value: 2_600 });
242+
Object.defineProperty(thread, "clientHeight", { configurable: true, value: 500 });
243+
pane.append(thread);
244+
let commitEffect: AfterCommitEffect | undefined;
245+
state.renderLifecycle.afterCommit = vi.fn((effect: AfterCommitEffect) => {
246+
commitEffect = effect;
247+
return vi.fn();
248+
});
249+
250+
pane.restoreOlderMessagesViewport("main", 420);
251+
commitEffect?.(vi.fn());
252+
253+
expect(thread.scrollTop).toBe(420);
254+
expect(pane.transcriptScrollTop).toBe(420);
255+
});
256+
161257
it("does not request older rows from a complete imported snapshot", () => {
162258
const client = { request: vi.fn() } as unknown as GatewayBrowserClient;
163259
const { pane, state } = createTestChatPane({ client, sessions: {} as SessionCapability });

0 commit comments

Comments
 (0)