From 8025a859f43dfdbed0c4e8160277e62011315af3 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Thu, 23 Jul 2026 17:54:27 +0200 Subject: [PATCH 1/4] perf: reuse the SDK singleton PushProcessor instead of allocating per call new PushProcessor(room.client) was allocated per room on every sync cycle (in the getUnreadInfo fallback path) and per component mount in RoomTimeline/ThreadDrawer/notifications. The SDK already exposes a cached singleton at mx.pushProcessor (client.ts:1293). Element Web uses the same pattern. Replace all five allocations and drop the now-unused imports. --- src/app/features/room/RoomTimeline.tsx | 4 ++-- src/app/features/room/ThreadDrawer.tsx | 3 +-- src/app/pages/client/BackgroundNotifications.tsx | 3 +-- src/app/pages/client/ClientNonUIFeatures.tsx | 3 +-- src/app/utils/room.ts | 3 +-- 5 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 4e7ef1850..152691c86 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -12,7 +12,7 @@ import { import type { Editor } from 'slate'; import { useAtomValue, useSetAtom, useStore } from 'jotai'; import type { Room } from '$types/matrix-sdk'; -import { PushProcessor, Direction, EventType } from '$types/matrix-sdk'; +import { Direction, EventType } from '$types/matrix-sdk'; import classNames from 'classnames'; import type { VListHandle } from 'virtua'; import { VList } from 'virtua'; @@ -428,7 +428,7 @@ export function RoomTimeline({ const optionalSpace = useSpaceOptionally(); const roomParents = useAtomValue(roomToParentsAtom); const imagePackRooms = useImagePackRooms(room.roomId, roomParents); - const pushProcessor = useMemo(() => new PushProcessor(mx), [mx]); + const pushProcessor = mx.pushProcessor; const parseMemberEvent = useMemberEventParser(); const replyDraftAtom = useMemo(() => roomIdToReplyDraftAtomFamily(room.roomId), [room.roomId]); diff --git a/src/app/features/room/ThreadDrawer.tsx b/src/app/features/room/ThreadDrawer.tsx index c7726fabc..6bd36d44d 100644 --- a/src/app/features/room/ThreadDrawer.tsx +++ b/src/app/features/room/ThreadDrawer.tsx @@ -7,7 +7,6 @@ import { Direction, MatrixEvent, MatrixEventEvent, - PushProcessor, ReceiptType, RelationType, RoomEvent, @@ -137,7 +136,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra (userId: string) => jotaiStore.get(profilesCacheAtom)[userId], [jotaiStore] ); - const pushProcessor = useMemo(() => new PushProcessor(mx), [mx]); + const pushProcessor = mx.pushProcessor; const useAuthentication = useMediaAuthentication(); const mentionClickHandler = useMentionClickHandler(room.roomId); const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); diff --git a/src/app/pages/client/BackgroundNotifications.tsx b/src/app/pages/client/BackgroundNotifications.tsx index be8cdc92c..c54b6ecc5 100644 --- a/src/app/pages/client/BackgroundNotifications.tsx +++ b/src/app/pages/client/BackgroundNotifications.tsx @@ -7,7 +7,6 @@ import { MatrixEventEvent, RoomEvent, SyncState, - PushProcessor, EventType, } from '$types/matrix-sdk'; @@ -327,7 +326,7 @@ export function BackgroundNotifications() { }); } - const pushProcessor = new PushProcessor(mx); + const pushProcessor = mx.pushProcessor; const handleAccountData = (event: MatrixEvent) => { if (event.getType() === (EventType.Direct as string)) { diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index b39ec1512..4cd4aa384 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -11,7 +11,6 @@ import { getPresenceSyncManager } from '$client/initMatrix'; import { MatrixEvent, MatrixEventEvent, - PushProcessor, RoomEvent, SetPresence, SyncState, @@ -339,7 +338,7 @@ function MessageNotifications() { }, []); useEffect(() => { - const pushProcessor = new PushProcessor(mx); + const pushProcessor = mx.pushProcessor; // Track encrypted events that should skip focus check when decrypted (because we // already checked focus when the encrypted event arrived, and want to use that // original state rather than re-checking after decryption completes). diff --git a/src/app/utils/room.ts b/src/app/utils/room.ts index 922a6bf91..7b8243554 100644 --- a/src/app/utils/room.ts +++ b/src/app/utils/room.ts @@ -16,7 +16,6 @@ import { EventTimeline, EventType, NotificationCountType, - PushProcessor, PushRuleActionName, RelationType, MsgType, @@ -427,7 +426,7 @@ export const getUnreadInfo = (room: Room, options?: UnreadInfoOptions): UnreadIn const liveEvents = room.getLiveTimeline().getEvents(); let fallbackTotal = 0; let fallbackHighlight = 0; - const pushProcessor = new PushProcessor(room.client); + const pushProcessor = room.client.pushProcessor; for (let i = liveEvents.length - 1; i >= 0; i -= 1) { const event = liveEvents[i]; if (!event) break; From 8fe281670732e8ac5a3d5b87f28a5c0f613af93a Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Thu, 23 Jul 2026 18:00:33 +0200 Subject: [PATCH 2/4] perf: narrow sync-settled unread recompute to dirty rooms only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sync-settled callback in useBindRoomToUnreadAtom called getUnreadInfos on ALL joined rooms every sync cycle (O(rooms × timeline × push_rules)). Element Web does not do this — it relies on incremental per-room RoomEvent.UnreadNotifications + RoomEvent.Timeline handlers. Track room IDs that received data in the sync response (onCacheRoomData) and pass them to the settled listener. Recompute unread only for those dirty rooms via getUnreadInfosForRooms, issuing targeted PUT/DELETE actions instead of a full RESET. The incremental handlers and the isResponseProcessing guard remain, so the 'SDK counts unreliable' fallback for rooms without read receipts is preserved. --- src/app/state/room/roomToUnread.ts | 21 ++++++++++------- src/app/utils/room.ts | 38 ++++++++++++++++++++++++++++++ src/client/slidingSync.test.ts | 2 +- src/client/slidingSync.ts | 19 ++++++++++++--- 4 files changed, 68 insertions(+), 12 deletions(-) diff --git a/src/app/state/room/roomToUnread.ts b/src/app/state/room/roomToUnread.ts index c3fb1cd43..c19e5f933 100644 --- a/src/app/state/room/roomToUnread.ts +++ b/src/app/state/room/roomToUnread.ts @@ -17,6 +17,7 @@ import { getNotificationType, getUnreadInfo, getUnreadInfos, + getUnreadInfosForRooms, isNotificationEvent, } from '$utils/room'; import { useSyncState } from '$hooks/useSyncState'; @@ -198,16 +199,20 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo useEffect(() => { const manager = getSlidingSyncManager(mx); if (!manager) return undefined; - return manager.subscribeToResponseSettled(() => { - setUnreadAtom({ - type: 'RESET', - unreadInfos: getUnreadInfos(mx, { - applyFixup: true, - mDirects, - }), + return manager.subscribeToResponseSettled((dirtyRoomIds) => { + if (dirtyRoomIds.size === 0) return; + const { unread, deleted } = getUnreadInfosForRooms(mx, dirtyRoomIds, { + applyFixup: true, + mDirects, }); + for (const roomId of deleted) { + publishUnreadAction({ type: 'DELETE', roomId }); + } + for (const unreadInfo of unread) { + publishUnreadAction({ type: 'PUT', unreadInfo }); + } }); - }, [mx, setUnreadAtom, mDirects]); + }, [mx, setUnreadAtom, publishUnreadAction, mDirects]); useEffect(() => { publishUnreadAction({ diff --git a/src/app/utils/room.ts b/src/app/utils/room.ts index 7b8243554..a9cf70323 100644 --- a/src/app/utils/room.ts +++ b/src/app/utils/room.ts @@ -516,6 +516,44 @@ export const getUnreadInfos = (mx: MatrixClient, options?: UnreadInfoOptions): U return unreadInfos; }; +export const getUnreadInfosForRooms = ( + mx: MatrixClient, + roomIds: Iterable, + options?: UnreadInfoOptions +): { unread: UnreadInfo[]; deleted: string[] } => { + const unread: UnreadInfo[] = []; + const deleted: string[] = []; + + for (const roomId of roomIds) { + const room = mx.getRoom(roomId); + if (!room) { + deleted.push(roomId); + continue; + } + if (room.isSpaceRoom()) { + deleted.push(roomId); + continue; + } + if (room.getMyMembership() !== 'join') { + deleted.push(roomId); + continue; + } + if (getNotificationType(mx, room.roomId) === NotificationType.Mute) { + deleted.push(roomId); + continue; + } + + const unreadInfo = getUnreadInfo(room, options); + if (unreadInfo.total > 0 || unreadInfo.highlight > 0) { + unread.push(unreadInfo); + } else { + deleted.push(roomId); + } + } + + return { unread, deleted }; +}; + export const getRoomAvatarUrl = ( mx: MatrixClient, room: Room, diff --git a/src/client/slidingSync.test.ts b/src/client/slidingSync.test.ts index 10eb46b45..c4937343e 100644 --- a/src/client/slidingSync.test.ts +++ b/src/client/slidingSync.test.ts @@ -137,7 +137,7 @@ describe('SlidingSyncManager initial request', () => { it('settles response processing after post-response work can finish', async () => { const manager = makeManager(makeMockMx()); - const settled = vi.fn<() => void>(); + const settled = vi.fn<(dirtyRoomIds: ReadonlySet) => void>(); manager.subscribeToResponseSettled(settled); manager.attach(); diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index d8ef816bf..b72b11304 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -245,6 +245,13 @@ export class SlidingSyncManager { private deferredImagePackSubscriptions: Set | null = null; + /** + * Room IDs that received data in the current sync cycle. Used to narrow the + * sync-settled unread recompute to only changed rooms instead of all rooms. + * Populated by onCacheRoomData, cleared after the settled listeners fire. + */ + private readonly dirtyRoomIds = new Set(); + private roomSubscriptionSyncQueued = false; private readonly roomTimelineLimit: number; @@ -294,7 +301,7 @@ export class SlidingSyncManager { private responseProcessing = false; - private readonly responseSettledListeners = new Set<() => void>(); + private readonly responseSettledListeners = new Set<(dirtyRoomIds: ReadonlySet) => void>(); private previousListCounts: Map = new Map(); @@ -496,7 +503,9 @@ export class SlidingSyncManager { globalThis.queueMicrotask(() => { if (this.disposed) return; this.responseProcessing = false; - this.responseSettledListeners.forEach((listener) => listener()); + const dirtyRoomIds = new Set(this.dirtyRoomIds); + this.dirtyRoomIds.clear(); + this.responseSettledListeners.forEach((listener) => listener(dirtyRoomIds)); }); }; @@ -515,6 +524,7 @@ export class SlidingSyncManager { }; this.onCacheRoomData = (roomId, data) => { + this.dirtyRoomIds.add(roomId); this.sidebarCache.cacheRoom(roomId, data); if (!this.initialListHydrationCompleted || this.hydratingSidebarCache) return; @@ -577,6 +587,7 @@ export class SlidingSyncManager { this.pendingRoomDataListeners.clear(); this.responseProcessing = false; this.responseSettledListeners.clear(); + this.dirtyRoomIds.clear(); this.roomDataAwaitingSyncCompletion.clear(); this.roomSubscriptionStatusListeners.forEach((listeners) => listeners.forEach((listener) => listener(false)) @@ -982,7 +993,9 @@ export class SlidingSyncManager { return this.responseProcessing; } - public subscribeToResponseSettled(listener: () => void): () => void { + public subscribeToResponseSettled( + listener: (dirtyRoomIds: ReadonlySet) => void + ): () => void { this.responseSettledListeners.add(listener); return () => this.responseSettledListeners.delete(listener); } From 7dfa6118ba279433aed886b1282415939576fd23 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Thu, 23 Jul 2026 11:44:34 -0500 Subject: [PATCH 3/4] fix: include receipts/account data in dirty rooms --- src/client/slidingSync.test.ts | 40 ++++++++++++++++++++++++++++++++++ src/client/slidingSync.ts | 11 ++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/client/slidingSync.test.ts b/src/client/slidingSync.test.ts index c4937343e..4e3e47dc4 100644 --- a/src/client/slidingSync.test.ts +++ b/src/client/slidingSync.test.ts @@ -153,6 +153,46 @@ describe('SlidingSyncManager initial request', () => { expect(settled).toHaveBeenCalledOnce(); }); + it('includes receipt-only and account-data-only rooms in the settled unread delta', async () => { + const manager = makeManager(makeMockMx()); + const settled = vi.fn<(dirtyRoomIds: ReadonlySet) => void>(); + manager.subscribeToResponseSettled(settled); + manager.attach(); + + fireLifecycle(SlidingSyncState.RequestFinished, {}); + fireLifecycle(SlidingSyncState.Complete, { + rooms: {}, + extensions: { + receipts: { + rooms: { + '!receipt:example.com': { + type: 'm.receipt', + content: {}, + }, + }, + }, + account_data: { + rooms: { + '!account-data:example.com': [ + { + type: EventType.FullyRead, + content: { event_id: '$event' }, + }, + ], + }, + }, + }, + }); + + await Promise.resolve(); + + expect(settled).toHaveBeenCalledOnce(); + expect([...settled.mock.calls[0]![0]]).toEqual([ + '!receipt:example.com', + '!account-data:example.com', + ]); + }); + it('does not fan out member requests for users referenced by startup sync', async () => { const getStateEvent = vi.fn<() => Promise>>().mockResolvedValue({ membership: KnownMembership.Join, diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index b72b11304..0b6aceabe 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -60,6 +60,10 @@ type SlidingSyncOptions = { initialRoomIds?: Iterable; }; +type RoomScopedExtensionResponse = { + rooms?: Record; +}; + export type SlidingSyncListDiagnostics = { key: string; knownCount: number; @@ -500,6 +504,13 @@ export class SlidingSyncManager { }); } + ['receipts', 'account_data'].forEach((extensionName) => { + const extension = resp.extensions?.[extensionName] as + | RoomScopedExtensionResponse + | undefined; + Object.keys(extension?.rooms ?? {}).forEach((roomId) => this.dirtyRoomIds.add(roomId)); + }); + globalThis.queueMicrotask(() => { if (this.disposed) return; this.responseProcessing = false; From 1502b4dc801b3528c3428225ed46cb5eb82670d1 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Thu, 23 Jul 2026 11:47:08 -0500 Subject: [PATCH 4/4] formatting --- src/client/slidingSync.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index 0b6aceabe..695514585 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -305,7 +305,9 @@ export class SlidingSyncManager { private responseProcessing = false; - private readonly responseSettledListeners = new Set<(dirtyRoomIds: ReadonlySet) => void>(); + private readonly responseSettledListeners = new Set< + (dirtyRoomIds: ReadonlySet) => void + >(); private previousListCounts: Map = new Map();