fix: scroll-to-bottom regression and timeline pagination fixes (#529)

### Description

Fixes several timeline bugs introduced after the
timeline-reset-on-navigation refactor:

- Scroll-to-bottom no longer gets stuck after navigating to a room
- Timeline pagination no longer uses a stale timeline chain after a
sliding sync reset
- URL preview requests are deduplicated so the same URL only fires one
network request
- Removed a redundant spidering call that was generating an extra
sliding sync request per room visit

Fixes #

#### Type of change

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my own code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings

### AI disclosure:

- [x] Partially AI assisted (GitHub Copilot)

`RoomTimeline.tsx`: Added a `liveTimelineLinked` guard so the initial
scroll doesn't fire with stale data from the previous room, and a
`pendingReadyRef` that defers `setIsReady(true)` when `processedEvents`
is still empty (preventing the room opening at position 0).
`useTimelineSync.ts`: A `useEffect` resets the timeline state on room
change so revisited rooms aren't stuck with `liveTimelineLinked =
false`. Reads `linkedTimelines` fresh after each `await` in pagination
so a sliding sync reset mid-paginate doesn't cause count comparisons on
a detached chain. A `continuing` flag prevents two concurrent pagination
calls from racing on the lock. URL preview dedup uses a module-level
`Map` to share in-flight promises for the same URL. Removed a redundant
`startSpidering` subscription call in the sync setup path.
This commit is contained in:
7w1 authored and GitHub committed 2026-03-28 10:23:55 -05:00
commit 748794cedc
9 files changed
+297 -44

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fix scroll-to-bottom after room navigation, timeline pagination reliability, and URL preview deduplication.
@@ -14,6 +14,23 @@ import { ImageViewer } from '../image-viewer';
const linkStyles = { color: color.Success.Main };
// Module-level in-flight deduplication: prevents N+1 concurrent requests when a
// large event batch renders many UrlPreviewCard instances for the same URL.
// Scoped by MatrixClient to avoid cross-account dedup if multiple clients exist.
// Inner cache keyed by URL only (not ts) — the same URL shows the same preview
// regardless of which message referenced it. Promises are evicted after settling
// so a later render can retry after network recovery.
const previewRequestCache = new WeakMap<any, Map<string, Promise<IPreviewUrlResponse>>>();
const getClientCache = (mx: any): Map<string, Promise<IPreviewUrlResponse>> => {
let clientCache = previewRequestCache.get(mx);
if (!clientCache) {
clientCache = new Map();
previewRequestCache.set(mx, clientCache);
}
return clientCache;
};
const openMediaInNewTab = async (url: string | undefined) => {
if (!url) {
console.warn('Attempted to open an empty url');
@@ -34,7 +51,13 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number; mediaType?: s
const [previewStatus, loadPreview] = useAsyncCallback(
useCallback(() => {
if (isDirect) return Promise.resolve(null);
return mx.getUrlPreview(url, ts);
const clientCache = getClientCache(mx);
const cached = clientCache.get(url);
if (cached !== undefined) return cached;
const urlPreview = mx.getUrlPreview(url, ts);
clientCache.set(url, urlPreview);
urlPreview.finally(() => clientCache.delete(url));
return urlPreview;
}, [url, ts, mx, isDirect])
);
+71 -9
View File
@@ -209,6 +209,14 @@ export function RoomTimeline({
const topSpacerHeightRef = useRef(0);
const mountScrollWindowRef = useRef<number>(Date.now() + 3000);
const hasInitialScrolledRef = useRef(false);
// Stored in a ref so eventsLength fluctuations (e.g. onLifecycle timeline reset
// firing within the window) cannot cancel it via useLayoutEffect cleanup.
const initialScrollTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
// Set to true when the 80 ms timer fires but processedEvents is still empty
// (e.g. the onLifecycle reset cleared the timeline before events refilled it).
// A recovery useLayoutEffect watches for processedEvents becoming non-empty
// and performs the final scroll + setIsReady when this flag is set.
const pendingReadyRef = useRef(false);
const currentRoomIdRef = useRef(room.roomId);
const [isReady, setIsReady] = useState(false);
@@ -217,6 +225,11 @@ export function RoomTimeline({
hasInitialScrolledRef.current = false;
mountScrollWindowRef.current = Date.now() + 3000;
currentRoomIdRef.current = room.roomId;
pendingReadyRef.current = false;
if (initialScrollTimerRef.current !== undefined) {
clearTimeout(initialScrollTimerRef.current);
initialScrollTimerRef.current = undefined;
}
setIsReady(false);
}
@@ -272,18 +285,45 @@ export function RoomTimeline({
!eventId &&
!hasInitialScrolledRef.current &&
timelineSync.eventsLength > 0 &&
// Guard: only scroll once the timeline reflects the current room's live
// timeline. Without this, a render with stale data from the previous room
// (before the room-change reset propagates) fires the scroll at the wrong
// position and marks hasInitialScrolledRef = true, preventing the correct
// scroll when the right data arrives.
timelineSync.liveTimelineLinked &&
vListRef.current
) {
vListRef.current.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
const t = setTimeout(() => {
vListRef.current?.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
setIsReady(true);
// Store in a ref rather than a local so subsequent eventsLength changes
// (e.g. the onLifecycle timeline reset firing within 80 ms) do NOT
// cancel this timer through the useLayoutEffect cleanup.
initialScrollTimerRef.current = setTimeout(() => {
initialScrollTimerRef.current = undefined;
if (processedEventsRef.current.length > 0) {
vListRef.current?.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
// Only mark ready once we've successfully scrolled. If processedEvents
// was empty when the timer fired (e.g. the onLifecycle reset cleared the
// timeline within the 80 ms window), defer setIsReady until the recovery
// effect below fires once events repopulate.
setIsReady(true);
} else {
pendingReadyRef.current = true;
}
}, 80);
hasInitialScrolledRef.current = true;
return () => clearTimeout(t);
}
return () => {};
}, [timelineSync.eventsLength, eventId, room.roomId]);
// No cleanup return — the timer must survive eventsLength fluctuations.
// It is cancelled on unmount by the dedicated effect below.
}, [timelineSync.eventsLength, timelineSync.liveTimelineLinked, eventId, room.roomId]);
// Cancel the initial-scroll timer on unmount (the useLayoutEffect above
// intentionally does not cancel it when deps change).
useEffect(
() => () => {
if (initialScrollTimerRef.current !== undefined) clearTimeout(initialScrollTimerRef.current);
},
[]
);
const recalcTopSpacer = useCallback(() => {
const v = vListRef.current;
@@ -357,6 +397,11 @@ export function RoomTimeline({
useEffect(() => {
if (eventId) return;
// Guard: once the timeline is visible to the user, do not override their
// scroll position. Without this, a later timeline refresh (e.g. the
// onLifecycle reset delivering a new linkedTimelines reference) can fire
// this effect after isReady and snap the view back to the read marker.
if (isReady) return;
const { readUptoEventId, inLiveTimeline, scrollTo } = unreadInfo ?? {};
if (readUptoEventId && inLiveTimeline && scrollTo) {
const evtTimeline = getEventTimeline(room, readUptoEventId);
@@ -368,12 +413,16 @@ export function RoomTimeline({
)
: undefined;
if (absoluteIndex !== undefined && vListRef.current) {
if (absoluteIndex !== undefined) {
const processedIndex = getRawIndexToProcessedIndex(absoluteIndex);
if (processedIndex !== undefined) {
if (processedIndex !== undefined && vListRef.current) {
vListRef.current.scrollToIndex(processedIndex, { align: 'start' });
setUnreadInfo((prev) => (prev ? { ...prev, scrollTo: false } : prev));
}
// Always consume the scroll intent once the event is located in the
// linked timelines, even if its processedIndex is undefined (filtered
// event). Without this, each linkedTimelines reference change retries
// the scroll indefinitely.
setUnreadInfo((prev) => (prev ? { ...prev, scrollTo: false } : prev));
}
}
}, [
@@ -381,6 +430,7 @@ export function RoomTimeline({
unreadInfo,
timelineSync.timeline.linkedTimelines,
eventId,
isReady,
getRawIndexToProcessedIndex,
]);
@@ -674,6 +724,18 @@ export function RoomTimeline({
processedEventsRef.current = processedEvents;
// Recovery: if the 80 ms initial-scroll timer fired while processedEvents was
// empty (timeline was mid-reset), scroll to bottom and reveal the timeline once
// events repopulate. Fires on every processedEvents.length change but is
// guarded by pendingReadyRef so it only acts once per initial-scroll attempt.
useLayoutEffect(() => {
if (!pendingReadyRef.current) return;
if (processedEvents.length === 0) return;
pendingReadyRef.current = false;
vListRef.current?.scrollToIndex(processedEvents.length - 1, { align: 'end' });
setIsReady(true);
}, [processedEvents.length]);
useEffect(() => {
if (!onEditLastMessageRef) return;
const ref = onEditLastMessageRef;
+115 -3
View File
@@ -40,12 +40,18 @@ function createTimeline(events: unknown[] = [{}]): FakeTimeline {
};
}
function createRoom(events: unknown[] = [{}]): {
function createRoom(
roomId = '!room:test',
events: unknown[] = [{}]
): {
room: FakeRoom;
timelineSet: FakeTimelineSet;
events: unknown[];
} {
const timeline = createTimeline(events);
const timeline = {
...createTimeline(events),
getRoomId: () => roomId,
};
const timelineSet = new EventEmitter() as FakeTimelineSet;
timelineSet.getLiveTimeline = () => timeline;
timelineSet.getTimelineForEvent = () => undefined;
@@ -55,7 +61,7 @@ function createRoom(events: unknown[] = [{}]): {
on: roomEmitter.on.bind(roomEmitter),
removeListener: roomEmitter.removeListener.bind(roomEmitter),
emit: roomEmitter.emit.bind(roomEmitter),
roomId: '!room:test',
roomId,
getUnfilteredTimelineSet: () => timelineSet as never,
getEventReadUpTo: () => null,
getThread: () => null,
@@ -125,4 +131,110 @@ describe('useTimelineSync', () => {
expect(scrollToBottom).toHaveBeenCalledWith('instant');
});
it('resets timeline state when room.roomId changes and eventId is not set', async () => {
const roomOne = createRoom('!room:one');
const roomTwo = createRoom('!room:two');
const scrollToBottom = vi.fn();
const { result, rerender } = renderHook(
({ room, eventId }) =>
useTimelineSync({
room,
mx: { getUserId: () => '@alice:test' } as never,
eventId,
isAtBottom: false,
isAtBottomRef: { current: false },
scrollToBottom,
unreadInfo: undefined,
setUnreadInfo: vi.fn(),
hideReadsRef: { current: false },
readUptoEventIdRef: { current: undefined },
}),
{
initialProps: {
room: roomOne.room as Room,
eventId: undefined as string | undefined,
},
}
);
expect(result.current.timeline.linkedTimelines[0]).toBe(roomOne.timelineSet.getLiveTimeline());
await act(async () => {
rerender({ room: roomTwo.room as Room, eventId: undefined });
await Promise.resolve();
});
expect(result.current.timeline.linkedTimelines[0]).toBe(roomTwo.timelineSet.getLiveTimeline());
});
it('does not reset timeline when eventId is set during a room change', async () => {
const roomOne = createRoom('!room:one');
const roomTwo = createRoom('!room:two');
const scrollToBottom = vi.fn();
const { result, rerender } = renderHook(
({ room, eventId }) =>
useTimelineSync({
room,
mx: { getUserId: () => '@alice:test' } as never,
eventId,
isAtBottom: false,
isAtBottomRef: { current: false },
scrollToBottom,
unreadInfo: undefined,
setUnreadInfo: vi.fn(),
hideReadsRef: { current: false },
readUptoEventIdRef: { current: undefined },
}),
{
initialProps: {
room: roomOne.room as Room,
eventId: undefined as string | undefined,
},
}
);
await act(async () => {
rerender({ room: roomTwo.room as Room, eventId: '$event:one' });
await Promise.resolve();
});
expect(result.current.timeline.linkedTimelines[0]).toBe(roomOne.timelineSet.getLiveTimeline());
});
it('does not reset timeline when the roomId stays the same', async () => {
const roomOne = createRoom('!room:one');
const sameRoomId = createRoom('!room:one');
const scrollToBottom = vi.fn();
const { result, rerender } = renderHook(
({ room }) =>
useTimelineSync({
room,
mx: { getUserId: () => '@alice:test' } as never,
eventId: undefined,
isAtBottom: false,
isAtBottomRef: { current: false },
scrollToBottom,
unreadInfo: undefined,
setUnreadInfo: vi.fn(),
hideReadsRef: { current: false },
readUptoEventIdRef: { current: undefined },
}),
{
initialProps: {
room: roomOne.room as Room,
},
}
);
await act(async () => {
rerender({ room: sameRoomId.room as Room });
await Promise.resolve();
});
expect(result.current.timeline.linkedTimelines[0]).toBe(roomOne.timelineSet.getLiveTimeline());
});
});
+51 -6
View File
@@ -147,6 +147,13 @@ const useTimelinePagination = (
(backwards ? setBackwardStatus : setForwardStatus)('loading');
}
// `continuing` tracks whether we hand the fetchingRef lock to a recursive
// continuation call below. The finally block must NOT reset the lock if
// the recursive call has already claimed it, otherwise there is a brief
// window where fetchingRef is false while the recursive paginate is in
// flight, allowing a third overlapping call to start on sparse pages.
let continuing = false;
try {
const countBefore = getTimelinesEventsCount(lTimelines);
@@ -172,25 +179,45 @@ const useTimelinePagination = (
}
if (alive()) {
recalibratePagination(lTimelines);
// Re-read linkedTimelines after the await: a sliding sync reset may have
// replaced lTimelines[0] (via resetLiveTimeline) while pagination was in
// flight, making the captured lTimelines stale. Using the fresh ref
// ensures recalibratePagination rebuilds from the current live chain and
// that countAfter/stillHasToken comparisons are meaningful.
const freshLTimelines = timelineRef.current.linkedTimelines;
recalibratePagination(freshLTimelines);
(backwards ? setBackwardStatus : setForwardStatus)('idle');
const countAfter = getTimelinesEventsCount(getLinkedTimelines(lTimelines[0]));
const countAfter = getTimelinesEventsCount(getLinkedTimelines(freshLTimelines[0]));
const fetched = countAfter - countBefore;
if (fetched > 0 && fetched < 5) {
const checkTimeline = backwards
? freshLTimelines[0]
: freshLTimelines[freshLTimelines.length - 1];
const checkDirection = backwards ? Direction.Backward : Direction.Forward;
const stillHasToken =
typeof getLinkedTimelines(lTimelines[0])[0]?.getPaginationToken(
Direction.Backward
) === 'string';
typeof getLinkedTimelines(checkTimeline)[0]?.getPaginationToken(checkDirection) ===
'string';
if (stillHasToken) {
// Release lock so inner paginate can claim it, then mark continuing
// so the finally block below does NOT reset it after inner claims.
fetchingRef.current[directionKey] = false;
continuing = true;
paginate(backwards);
// At this point the inner paginate has synchronously set
// fetchingRef.current[directionKey] = true before hitting its own
// await. The finally below will skip the reset.
}
}
}
} finally {
fetchingRef.current[directionKey] = false;
// Only release the lock if we did NOT hand it to a recursive continuation.
// If `continuing` is true the recursive call owns the lock and will release
// it in its own finally block.
if (!continuing) {
fetchingRef.current[directionKey] = false;
}
}
};
}, [mx, alive, setTimeline, limit, setBackwardStatus, setForwardStatus]);
@@ -548,6 +575,24 @@ export function useTimelineSync({
setTimeline({ linkedTimelines: getInitialTimeline(room).linkedTimelines });
}, [eventId, room, timeline.linkedTimelines.length]);
// When navigating between rooms, reset the timeline state to the new room's
// initial linked timelines. Without this, the component's timeline state
// retains stale data from the previous room, causing liveTimelineLinked to be
// false until a TimelineReset event fires. For revisited rooms with up-to-date
// data (no initial:true in the sliding sync response), that event may never
// arrive — leaving the initial-scroll guard permanently blocked and the room
// invisible.
const prevRoomIdRef = useRef(room.roomId);
useEffect(() => {
if (prevRoomIdRef.current === room.roomId) return;
prevRoomIdRef.current = room.roomId;
if (eventId) return;
setTimeline({ linkedTimelines: getInitialTimeline(room).linkedTimelines });
// Intentionally only depends on room: we want this to fire when the room
// identity changes, not on every eventId change.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [room]);
return {
timeline,
setTimeline,
+2 -11
View File
@@ -24,16 +24,7 @@ export const useSlidingSyncActiveRoom = (): void => {
const manager = getSlidingSyncManager(mx);
if (!manager) return undefined;
// Wait for the room to be initialized from list sync before subscribing
// with the full timeline limit. This prevents timeline ordering issues where
// the room might be receiving events from list expansion while we're also
// trying to load a large timeline, causing events to be added out of order.
const timeoutId = setTimeout(() => {
manager.subscribeToRoom(roomId);
}, 100);
return () => {
clearTimeout(timeoutId);
};
manager.subscribeToRoom(roomId);
return undefined;
}, [mx, roomId]);
};
+7 -11
View File
@@ -22,18 +22,14 @@ export const getFirstLinkedTimeline = (
return current;
};
const collectTimelines = (
tl: EventTimeline | null,
dir: Direction,
acc: EventTimeline[] = []
): EventTimeline[] => {
if (!tl) return acc;
return collectTimelines(tl.getNeighbouringTimeline(dir), dir, [...acc, tl]);
};
export const getLinkedTimelines = (timeline: EventTimeline): EventTimeline[] => {
const firstTimeline = getFirstLinkedTimeline(timeline, Direction.Backward);
return collectTimelines(firstTimeline, Direction.Forward);
const result: EventTimeline[] = [];
let current: EventTimeline | null = getFirstLinkedTimeline(timeline, Direction.Backward);
while (current) {
result.push(current);
current = current.getNeighbouringTimeline(Direction.Forward);
}
return result;
};
export const timelineToEventsCount = (t: EventTimeline) => {
-3
View File
@@ -563,9 +563,6 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig):
pollTimeoutMs: slidingConfig?.pollTimeoutMs ?? SLIDING_SYNC_POLL_TIMEOUT_MS,
});
manager.attach();
// Begin background spidering so all rooms are eventually indexed.
// Not awaited — this runs incrementally in the background.
manager.startSpidering(100, 50);
slidingSyncByClient.set(mx, manager);
syncTransportByClient.set(mx, {
transport: 'sliding',
+22
View File
@@ -8,6 +8,7 @@ import {
MSC3575List,
MSC3575RoomData,
MSC3575RoomSubscription,
MSC3575SlidingSyncResponse,
MSC3575_WILDCARD,
RoomMemberEvent,
SlidingSync,
@@ -351,6 +352,27 @@ export class SlidingSyncManager {
return;
}
// Before room data is processed, reset live timelines for active rooms that
// are receiving a full refresh (initial: true) or a post-gap update
// (limited: true). The SDK deliberately does not call resetLiveTimeline() for
// sliding sync, so events from previous visits accumulate in the live
// timeline alongside new events. Resetting here — before the SDK's
// onRoomData listener runs — ensures the fresh batch lands on a clean
// timeline with a correct backward pagination token.
if (state === SlidingSyncState.RequestFinished && resp && !err) {
const rooms = (resp as MSC3575SlidingSyncResponse).rooms ?? {};
Object.entries(rooms)
.filter(([, roomData]) => roomData.initial || roomData.limited)
.filter(([roomId]) => this.activeRoomSubscriptions.has(roomId))
.forEach(([roomId]) => {
const room = this.mx.getRoom(roomId);
if (!room) return;
const timelineSet = room.getUnfilteredTimelineSet();
if (timelineSet.getLiveTimeline().getEvents().length === 0) return;
timelineSet.resetLiveTimeline();
});
}
if (err || !resp || state !== SlidingSyncState.Complete) return;
// Track what changed in this sync cycle