Skip to content

Commit 54e50ba

Browse files
authored
refactor(ui): simplify chat history pagination (#124921)
1 parent e2cefa8 commit 54e50ba

16 files changed

Lines changed: 60 additions & 57 deletions

‎ui/src/pages/chat/chat-gateway.abort-diagnostic.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ type AbortDiagnosticState = ChatState & {
1818
function createAbortDiagnosticState(runId = "run-validation-abort"): AbortDiagnosticState {
1919
return {
2020
chatAttachments: [],
21+
chatHistoryPagination: { hasMore: false },
2122
chatLoading: false,
2223
chatMessage: "",
2324
chatMessages: [],

‎ui/src/pages/chat/chat-gateway.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
function createState(overrides: Partial<ChatState> = {}): ChatState {
2020
return {
2121
chatAttachments: [],
22+
chatHistoryPagination: { hasMore: false },
2223
chatLoading: false,
2324
chatMessage: "",
2425
chatMessages: [],

‎ui/src/pages/chat/chat-history-subscription-disposal.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ function createSubscriptionState(
2121
connected: true,
2222
connectionEpoch: 1,
2323
sessionKey: subscription.key,
24+
chatHistoryPagination: { hasMore: false },
2425
chatLoading: false,
2526
chatMessages: [],
2627
chatThinkingLevel: null,

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

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -511,16 +511,16 @@ function resolveChatHistorySessionId(result: ChatHistoryResult): string | null {
511511
: null;
512512
}
513513

514-
function retainedRawHistoryStart(pagination: ChatHistoryPagination | undefined): number | null {
515-
const totalMessages = pagination?.totalMessages;
514+
function retainedRawHistoryStart(pagination: ChatHistoryPagination): number | null {
515+
const totalMessages = pagination.totalMessages;
516516
if (
517517
typeof totalMessages !== "number" ||
518518
!Number.isSafeInteger(totalMessages) ||
519519
totalMessages < 0
520520
) {
521521
return null;
522522
}
523-
const retainedDepth = pagination?.hasMore ? pagination.nextOffset : totalMessages;
523+
const retainedDepth = pagination.hasMore ? pagination.nextOffset : totalMessages;
524524
const start = totalMessages - retainedDepth + 1;
525525
return Number.isSafeInteger(start) && start > 0 ? start : null;
526526
}
@@ -530,7 +530,7 @@ function reconcileLoadedHistoryTail(options: {
530530
nextPagination: ChatHistoryPagination;
531531
nextSessionId: string | null;
532532
previousMessages: unknown[];
533-
previousPagination: ChatHistoryPagination | undefined;
533+
previousPagination: ChatHistoryPagination;
534534
previousSessionId: string | null;
535535
}): { messages: unknown[]; pagination: ChatHistoryPagination } | null {
536536
if (
@@ -540,7 +540,7 @@ function reconcileLoadedHistoryTail(options: {
540540
) {
541541
return null;
542542
}
543-
const previousTotal = options.previousPagination?.totalMessages;
543+
const previousTotal = options.previousPagination.totalMessages;
544544
const nextTotal = options.nextPagination.totalMessages;
545545
const previousStart = retainedRawHistoryStart(options.previousPagination);
546546
const nextStart = retainedRawHistoryStart(options.nextPagination);
@@ -1036,7 +1036,7 @@ function replaceCachedChatMessages(state: ChatState, sessionKey: string, agentId
10361036
? { displayedLeafEntryId: state.chatDisplayedLeafEntryId }
10371037
: {}),
10381038
messages: state.chatMessages,
1039-
pagination: state.chatHistoryPagination ?? { hasMore: false },
1039+
pagination: state.chatHistoryPagination,
10401040
sessionId: state.currentSessionId ?? null,
10411041
},
10421042
);

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

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ import { PollController } from "../../lit/poll-controller.ts";
3838
import { SubscriptionsController } from "../../lit/subscriptions-controller.ts";
3939
import type { BoardChatDockSize } from "./board-session-surface.ts";
4040
import { ChatComposerCapabilityHost } from "./chat-composer-capability-host.ts";
41-
import type { ChatHistoryPagination } from "./chat-history-pagination.ts";
4241
import { sendSessionObserverVisibility } from "./chat-observer.ts";
4342
import {
4443
boardChatDockLayout,
@@ -379,12 +378,10 @@ export abstract class ChatPaneBase extends OpenClawLightDomElement {
379378
protected historyIntentTimer: number | null = null;
380379
protected historyTouchY: number | null = null;
381380
protected transcriptScrollTop: number | null = null;
382-
protected nativePaginationSnapshot: ChatHistoryPagination | null = null;
383381
// Older cursors already requested this session. A provider that cycles cursors
384382
// (c1 -> c2 -> c1) on empty/duplicate pages would otherwise loop forever, since
385383
// the sentinel never scrolls out of view when nothing new renders.
386384
protected readonly olderCursorsSeen = new Set<string>();
387-
protected readonly olderOffsetsSeen = new Set<number>();
388385

389386
constructor() {
390387
super();

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

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ describe("chat pane catalog session lifecycle", () => {
236236
const readPage: SessionsCatalogReadResult = {
237237
hostId: "gateway:local",
238238
threadId: "thread-1",
239-
items: [{ id: "u1", type: "userMessage", text: "hi" }],
239+
items: [{ id: "x1", type: "other" }],
240240
// Same cursor the request was made with: a stale provider that would loop.
241241
nextCursor: "cursor-1",
242242
};
@@ -259,6 +259,31 @@ describe("chat pane catalog session lifecycle", () => {
259259
expect(pane.catalogCursor).toBeUndefined();
260260
});
261261

262+
it("counts visible messages on an exhausted final page as progress", async () => {
263+
const readPage: SessionsCatalogReadResult = {
264+
hostId: "gateway:local",
265+
threadId: "thread-1",
266+
items: [{ id: "u1", type: "userMessage", text: "oldest message" }],
267+
};
268+
const client = {
269+
request: vi.fn(async () => readPage),
270+
} as unknown as GatewayBrowserClient;
271+
const { pane, state } = createTestChatPane({ client, sessions: {} as SessionCapability });
272+
const key = "catalog:claude:gateway%3Alocal:thread-1";
273+
state.sessionKey = key;
274+
pane.sessionKey = key;
275+
pane.catalogCursor = "final-page";
276+
277+
const progressed = await pane.loadCatalogSession(
278+
{ catalogId: "claude", hostId: "gateway:local", threadId: "thread-1" },
279+
true,
280+
);
281+
282+
expect(progressed).toBe(true);
283+
expect(pane.catalogMessages).toHaveLength(1);
284+
expect(pane.catalogCursor).toBeUndefined();
285+
});
286+
262287
it("keeps paging when an advancing older page renders nothing new", async () => {
263288
const readPage: SessionsCatalogReadResult = {
264289
hostId: "gateway:local",

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

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ type TestChatPane = HTMLElement & {
3333
currentReplyNavigationId: (sessionKey: string) => string | null;
3434
hasOlderMessages: () => boolean;
3535
loadingOlder: boolean;
36-
olderOffsetsSeen: Set<number>;
3736
resetOlderMessagesViewport: () => void;
3837
readonly updateComplete: Promise<boolean>;
3938
transcriptScrollTop: number | null;
@@ -688,9 +687,6 @@ describe("chat pane native history pagination", () => {
688687
nativeHistoryMessage(4),
689688
];
690689
state.chatHistoryPagination = { hasMore: false, totalMessages: 4 };
691-
pane.olderOffsetsSeen.add(2);
692-
pane.olderOffsetsSeen.add(4);
693-
694690
await loadChatHistory(state);
695691

696692
expect(state.chatMessages.map(nativeHistorySeq)).toEqual([1, 2, 3, 4]);
@@ -699,7 +695,6 @@ describe("chat pane native history pagination", () => {
699695
totalMessages: 4,
700696
});
701697
expect(pane.hasOlderMessages()).toBe(false);
702-
expect(pane.olderOffsetsSeen).toEqual(new Set());
703698
});
704699

705700
it("keeps projected siblings while replacing the overlapping tail", async () => {

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

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,7 @@ export abstract class ChatPaneHistory extends ChatPaneReplyNavigation {
5656
if (parseCatalogSessionKey(state.sessionKey)) {
5757
return Boolean(this.catalogCursor && !this.catalogLoading);
5858
}
59-
const pagination = state.chatHistoryPagination ?? { hasMore: false };
60-
if (pagination !== this.nativePaginationSnapshot) {
61-
this.nativePaginationSnapshot = pagination;
62-
this.olderOffsetsSeen.clear();
63-
}
64-
return pagination.hasMore && !state.chatLoading;
59+
return state.chatHistoryPagination.hasMore && !state.chatLoading;
6560
}
6661

6762
protected resetOlderMessagesViewport(): void {
@@ -80,8 +75,6 @@ export abstract class ChatPaneHistory extends ChatPaneReplyNavigation {
8075
}
8176
this.transcriptScrollTop = null;
8277
this.olderCursorsSeen.clear();
83-
this.olderOffsetsSeen.clear();
84-
this.nativePaginationSnapshot = null;
8578
this.clearHistoryObserver();
8679
}
8780

@@ -328,18 +321,15 @@ export abstract class ChatPaneHistory extends ChatPaneReplyNavigation {
328321
let prepended = false;
329322
try {
330323
if (catalogKey) {
331-
const previousCount = this.catalogMessages.length;
332-
const progressed = await this.loadCatalogSession(catalogKey, true);
333-
prepended = progressed || this.catalogMessages.length > previousCount;
324+
prepended = await this.loadCatalogSession(catalogKey, true);
334325
} else {
335326
const pagination = state.chatHistoryPagination;
336-
if (!pagination?.hasMore) {
327+
if (!pagination.hasMore) {
337328
return false;
338329
}
339330
const requestedOffset = pagination.nextOffset;
340331
const expectedSessionId =
341332
typeof state.currentSessionId === "string" ? state.currentSessionId.trim() : "";
342-
this.olderOffsetsSeen.add(requestedOffset);
343333
const result = await loadOlderChatHistoryPage(state, requestedOffset);
344334
if (!result || generation !== this.olderLoadGeneration) {
345335
return false;
@@ -358,10 +348,7 @@ export abstract class ChatPaneHistory extends ChatPaneReplyNavigation {
358348
return true;
359349
}
360350
const nextPagination = resolveChatHistoryPagination(result);
361-
const exhausted =
362-
!nextPagination.hasMore ||
363-
nextPagination.nextOffset <= requestedOffset ||
364-
this.olderOffsetsSeen.has(nextPagination.nextOffset);
351+
const exhausted = !nextPagination.hasMore || nextPagination.nextOffset <= requestedOffset;
365352
const messages = Array.isArray(result.messages) ? result.messages : [];
366353
const nextMessages = this.prependUniqueNativeMessages(messages, state.chatMessages);
367354
const grew = nextMessages.length > state.chatMessages.length;
@@ -375,7 +362,6 @@ export abstract class ChatPaneHistory extends ChatPaneReplyNavigation {
375362
}
376363
: nextPagination;
377364
state.chatHistoryPagination = appliedPagination;
378-
this.nativePaginationSnapshot = appliedPagination;
379365
state.lastError = null;
380366
scheduleChatScroll(state, false);
381367
prepended = grew || !exhausted;

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ export class ChatPane extends ChatPaneBrowserAnnotationRender {
285285
const attachmentReadSignal = attachmentReads.readSignal;
286286
const historyHasMore = catalogKey
287287
? Boolean(this.catalogCursor)
288-
: state.chatHistoryPagination?.hasMore === true;
288+
: state.chatHistoryPagination.hasMore;
289289
const sessionActionCallbacks = createChatPaneSessionActionCallbacks({
290290
getSnapshot: () => this.context.gateway.snapshot,
291291
hasLocalRun: () => Boolean(state.chatRunId),

‎ui/src/pages/chat/chat-pane-reply-navigation.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ export abstract class ChatPaneReplyNavigation extends ChatPaneSession {
146146
if (!this.replyNavigationIsCurrent(navigation, state, sessionKey, sessionId)) {
147147
return;
148148
}
149-
if (!state.chatHistoryPagination?.hasMore) {
149+
if (!state.chatHistoryPagination.hasMore) {
150150
if (this.replyNavigationIsCurrent(navigation, state, sessionKey, sessionId)) {
151151
state.lastError = t("chat.messages.originalUnavailable");
152152
state.requestUpdate?.();
@@ -158,7 +158,7 @@ export abstract class ChatPaneReplyNavigation extends ChatPaneSession {
158158
return;
159159
}
160160
if (!loaded) {
161-
if (!state.chatHistoryPagination?.hasMore && !state.lastError) {
161+
if (!state.chatHistoryPagination.hasMore && !state.lastError) {
162162
state.lastError = t("chat.messages.originalUnavailable");
163163
state.requestUpdate?.();
164164
}

0 commit comments

Comments
 (0)