From a4445e96ba544890e1a0ecf5a51cea4e562a7e02 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Mon, 17 Aug 2026 22:04:35 +0200 Subject: [PATCH] fix(sliding-sync): keep the head back-pagination token on overlapping limited responses --- src/client/slidingSync.ts | 9 ++++++ .../slidingSyncTimelineReconciliation.test.ts | 31 +++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index aea104cf1..a18389f40 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -428,6 +428,15 @@ export const prepareSlidingSyncTimelines = ( continue; } + // The SDK writes prev_batch over the live timeline's BACKWARDS token on every + // limited response. When the window starts at an event we already have below + // our top, nothing is prepended and the top does not move, so that token would + // back-paginate from the wrong stream position and prepend newer events. + if (timelineData.limited === true && firstKnownResponseIndex === 0 && firstKnownLiveIndex > 0) { + const topToken = liveTimeline?.getPaginationToken(EventTimeline.BACKWARDS); + if (typeof topToken === 'string') timelineData.prev_batch = topToken; + } + if (!shouldMarkLimited) { continue; } diff --git a/src/client/slidingSyncTimelineReconciliation.test.ts b/src/client/slidingSyncTimelineReconciliation.test.ts index 7ea3284ba..7f9907eda 100644 --- a/src/client/slidingSyncTimelineReconciliation.test.ts +++ b/src/client/slidingSyncTimelineReconciliation.test.ts @@ -600,6 +600,37 @@ describe('timeline reconciliation in matrix-js-sdk', () => { expect(timelineIds(mx)).toEqual(['$e3', '$e4']); }); + it('keeps the top-of-timeline token when a limited response overlaps mid-timeline', async () => { + const { mx, deliver } = makeSdk(); + await deliver(roomId, { + initial: true, + required_state: [], + timeline: history, + limited: true, + prev_batch: 'top-token', + } as unknown as MSC3575RoomData); + const room = mx.getRoom(roomId)!; + expect(room.getLiveTimeline().getPaginationToken(EventTimeline.BACKWARDS)).toBe('top-token'); + + const roomData = { + required_state: [], + timeline: [newest, message('$e4', 400)], + limited: true, + prev_batch: 'mid-token', + } as unknown as MSC3575RoomData; + const resp = { + pos: 'p4', + rooms: { [roomId]: roomData }, + } as unknown as MSC3575SlidingSyncResponse; + prepareSlidingSyncTimelines(resp, mx); + await deliver(roomId, roomData); + + expect(timelineIds(mx)).toEqual(['$e1', '$e2', '$e3', '$e4']); + // 'mid-token' paginates back from $e3, so it would prepend above $e1 events + // that belong below it. + expect(room.getLiveTimeline().getPaginationToken(EventTimeline.BACKWARDS)).toBe('top-token'); + }); + it('keeps a usable back-pagination token after reconciling', async () => { const { mx, deliver } = makeSdk(); await deliver(roomId, initialRoomData(newest));