From 0e076485cd8af1efa3387226426afea34e9e7fe4 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 3 Mar 2026 00:05:46 -0500 Subject: [PATCH] Various fixes for UI/Rendering issues in sliding sync --- .../developer-tools/DevelopTools.tsx | 110 +++++++++++++++++- .../room/message/EncryptedContent.tsx | 7 ++ .../developer-tools/SyncDiagnostics.tsx | 61 +++++++++- src/app/state/room/roomToUnread.ts | 56 +++++++++ src/app/utils/notifications.ts | 12 ++ src/app/utils/room.ts | 29 ++++- src/client/slidingSync.ts | 14 ++- 7 files changed, 280 insertions(+), 9 deletions(-) diff --git a/src/app/features/common-settings/developer-tools/DevelopTools.tsx b/src/app/features/common-settings/developer-tools/DevelopTools.tsx index 7925d44a..1d4c53e0 100644 --- a/src/app/features/common-settings/developer-tools/DevelopTools.tsx +++ b/src/app/features/common-settings/developer-tools/DevelopTools.tsx @@ -1,4 +1,5 @@ -import { useCallback, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useAtomValue } from 'jotai'; import { Box, Text, @@ -12,6 +13,7 @@ import { config, color, } from 'folds'; +import { EventType, NotificationCountType } from '$types/matrix-sdk'; import { Page, PageContent, PageHeader } from '$components/page'; import { SequenceCard } from '$components/sequence-card'; import { SettingTile } from '$components/setting-tile'; @@ -21,6 +23,8 @@ import { copyToClipboard } from '$utils/dom'; import { useRoom } from '$hooks/useRoom'; import { useRoomState } from '$hooks/useRoomState'; import { useRoomAccountData } from '$hooks/useRoomAccountData'; +import { roomToUnreadAtom } from '$state/room/roomToUnread'; +import { isNotificationEvent } from '$utils/room'; import { CutoutCard } from '$components/cutout-card'; import { AccountDataEditor, AccountDataSubmitCallback } from '$components/AccountDataEditor'; import { useMatrixClient } from '$hooks/useMatrixClient'; @@ -46,6 +50,61 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { const [expandAccountData, setExpandAccountData] = useState(false); const [accountDataType, setAccountDataType] = useState(); + const roomToUnread = useAtomValue(roomToUnreadAtom); + const [, setTick] = useState(0); + + useEffect(() => { + const intervalId = window.setInterval(() => setTick((v) => v + 1), 1000); + return () => window.clearInterval(intervalId); + }, []); + + const unreadDiagnostics = useMemo(() => { + const userId = mx.getUserId(); + const liveEvents = room.getLiveTimeline().getEvents(); + const latestLiveEvent = liveEvents[liveEvents.length - 1]; + const latestLiveEventId = latestLiveEvent?.getId() ?? null; + const latestNotificationEvent = [...liveEvents] + .reverse() + .find((event) => isNotificationEvent(event)); + const latestNotificationEventId = latestNotificationEvent?.getId() ?? null; + const fullyReadEventId = + room.getAccountData(EventType.FullyRead)?.getContent<{ event_id?: string }>()?.event_id ?? + null; + const readUpToEventId = userId ? (room.getEventReadUpTo(userId) ?? null) : null; + const sdkUnreadTotal = room.getUnreadNotificationCount(NotificationCountType.Total); + const sdkUnreadHighlight = room.getUnreadNotificationCount(NotificationCountType.Highlight); + const atomUnread = roomToUnread.get(room.roomId); + + return { + roomId: room.roomId, + userId: userId ?? null, + timelineSize: liveEvents.length, + latestLiveEventId, + latestNotificationEventId, + fullyReadEventId, + readUpToEventId, + hasReadLatestLive: !!( + userId && + latestLiveEventId && + room.hasUserReadEvent(userId, latestLiveEventId) + ), + hasReadLatestNotification: !!( + userId && + latestNotificationEventId && + room.hasUserReadEvent(userId, latestNotificationEventId) + ), + sdkUnread: { + total: sdkUnreadTotal, + highlight: sdkUnreadHighlight, + }, + atomUnread: atomUnread + ? { + total: atomUnread.total, + highlight: atomUnread.highlight, + } + : null, + }; + }, [mx, room, roomToUnread]); const handleClose = useCallback(() => { setOpenStateEvent(undefined); @@ -203,6 +262,55 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { /> {expandState && ( + + + Unread Diagnostics + + + + `readUpTo`: {unreadDiagnostics.readUpToEventId ?? 'null'} + + + `m.fully_read`: {unreadDiagnostics.fullyReadEventId ?? 'null'} + + + Latest live: {unreadDiagnostics.latestLiveEventId ?? 'null'} | read?{' '} + {unreadDiagnostics.hasReadLatestLive ? 'yes' : 'no'} + + + Latest notification:{' '} + {unreadDiagnostics.latestNotificationEventId ?? 'null'} | read?{' '} + {unreadDiagnostics.hasReadLatestNotification ? 'yes' : 'no'} + + + SDK unread: {unreadDiagnostics.sdkUnread.total} total /{' '} + {unreadDiagnostics.sdkUnread.highlight} highlight + + + Atom unread:{' '} + {unreadDiagnostics.atomUnread + ? `${unreadDiagnostics.atomUnread.total} total / ${unreadDiagnostics.atomUnread.highlight} highlight` + : 'none'} + + Events Total: {roomState.size} diff --git a/src/app/features/room/message/EncryptedContent.tsx b/src/app/features/room/message/EncryptedContent.tsx index e0084d08..ddd82db4 100644 --- a/src/app/features/room/message/EncryptedContent.tsx +++ b/src/app/features/room/message/EncryptedContent.tsx @@ -1,6 +1,7 @@ import { MatrixEvent, MatrixEventEvent, MatrixEventHandlerMap } from '$types/matrix-sdk'; import { ReactNode, useEffect, useState } from 'react'; import { MessageEvent } from '$types/matrix/room'; +import { useMatrixClient } from '$hooks/useMatrixClient'; type EncryptedContentProps = { mEvent: MatrixEvent; @@ -8,8 +9,14 @@ type EncryptedContentProps = { }; export function EncryptedContent({ mEvent, children }: EncryptedContentProps) { + const mx = useMatrixClient(); const [, toggleEncrypted] = useState(mEvent.getType() === MessageEvent.RoomMessageEncrypted); + useEffect(() => { + if (mEvent.getType() !== MessageEvent.RoomMessageEncrypted) return; + mx.decryptEventIfNeeded(mEvent).catch(() => undefined); + }, [mx, mEvent]); + useEffect(() => { toggleEncrypted(mEvent.getType() === MessageEvent.RoomMessageEncrypted); const handleDecrypted: MatrixEventHandlerMap[MatrixEventEvent.Decrypted] = (event) => { diff --git a/src/app/features/settings/developer-tools/SyncDiagnostics.tsx b/src/app/features/settings/developer-tools/SyncDiagnostics.tsx index 54c0576c..83c521a5 100644 --- a/src/app/features/settings/developer-tools/SyncDiagnostics.tsx +++ b/src/app/features/settings/developer-tools/SyncDiagnostics.tsx @@ -3,9 +3,10 @@ import { Box, Text } from 'folds'; import { SequenceCard } from '$components/sequence-card'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { getClientSyncDiagnostics } from '$client/initMatrix'; -import { Direction, Room } from '$types/matrix-sdk'; +import { Direction, EventType, NotificationCountType, Room } from '$types/matrix-sdk'; import { Membership } from '$types/matrix/room'; import { SequenceCardStyle } from '$features/settings/styles.css'; +import { isNotificationEvent } from '$utils/room'; type RoomRenderingDiagnostics = { totalRooms: number; @@ -17,6 +18,16 @@ type RoomRenderingDiagnostics = { roomsWithBackPagination: number; }; +type UnreadDriftRoom = { + roomId: string; + roomName: string; + sdkTotal: number; + sdkHighlight: number; + latestNotificationEventId: string | null; + readUpToEventId: string | null; + fullyReadEventId: string | null; +}; + const getRoomRenderingDiagnostics = (rooms: Room[]): RoomRenderingDiagnostics => { let joinedRooms = 0; let inviteRooms = 0; @@ -52,6 +63,45 @@ const getRoomRenderingDiagnostics = (rooms: Room[]): RoomRenderingDiagnostics => }; }; +const getUnreadDriftRooms = (mx: ReturnType): UnreadDriftRoom[] => { + const userId = mx.getUserId(); + if (!userId) return []; + + return mx + .getRooms() + .filter((room) => !room.isSpaceRoom() && room.getMyMembership() === Membership.Join) + .reduce((driftRooms, room) => { + const sdkTotal = room.getUnreadNotificationCount(NotificationCountType.Total); + const sdkHighlight = room.getUnreadNotificationCount(NotificationCountType.Highlight); + if (sdkTotal <= 0 && sdkHighlight <= 0) return driftRooms; + + const latestNotificationEvent = [...room.getLiveTimeline().getEvents()] + .reverse() + .find((event) => !event.isSending() && isNotificationEvent(event)); + const latestNotificationEventId = latestNotificationEvent?.getId() ?? null; + if (!latestNotificationEventId) return driftRooms; + + const hasReadLatestNotification = room.hasUserReadEvent(userId, latestNotificationEventId); + if (!hasReadLatestNotification || sdkHighlight > 0) return driftRooms; + + const readUpToEventId = room.getEventReadUpTo(userId) ?? null; + const fullyReadEventId = + room.getAccountData(EventType.FullyRead)?.getContent<{ event_id?: string }>()?.event_id ?? + null; + + driftRooms.push({ + roomId: room.roomId, + roomName: room.name || room.roomId, + sdkTotal, + sdkHighlight, + latestNotificationEventId, + readUpToEventId, + fullyReadEventId, + }); + return driftRooms; + }, []); +}; + const formatListCoverage = (knownCount: number, rangeEnd: number): string => { if (knownCount <= 0) return '0/0'; const loadedCount = Math.max(0, Math.min(knownCount, rangeEnd + 1)); @@ -69,6 +119,7 @@ export function SyncDiagnostics() { const diagnostics = getClientSyncDiagnostics(mx); const roomDiagnostics = getRoomRenderingDiagnostics(mx.getRooms()); + const unreadDriftRooms = getUnreadDriftRooms(mx); return ( @@ -100,6 +151,14 @@ export function SyncDiagnostics() { Rooms with more history to paginate: {roomDiagnostics.roomsWithBackPagination} + Unread drift rooms: {unreadDriftRooms.length} + {unreadDriftRooms.slice(0, 10).map((room) => ( + + {room.roomName}: sdk {room.sdkTotal}/{room.sdkHighlight} | latest{' '} + {room.latestNotificationEventId ?? 'null'} | readUpTo {room.readUpToEventId ?? 'null'}{' '} + | fullyRead {room.fullyReadEventId ?? 'null'} + + ))} {diagnostics.sliding && ( <> diff --git a/src/app/state/room/roomToUnread.ts b/src/app/state/room/roomToUnread.ts index 38100de6..007e520b 100644 --- a/src/app/state/room/roomToUnread.ts +++ b/src/app/state/room/roomToUnread.ts @@ -9,6 +9,7 @@ import { SyncState, ReceiptContent, ReceiptType, + EventType, } from '$types/matrix-sdk'; import { useCallback, useEffect } from 'react'; import { @@ -134,6 +135,21 @@ export const roomToUnreadAtom = atom + deleteUnreadInfo( + draftRoomToUnread, + getAllParents(get(roomToParentsAtom), unreadInfo.roomId), + unreadInfo.roomId + ) + ) + ); + } + return; + } const currentUnread = get(baseRoomToUnread).get(unreadInfo.roomId); if (currentUnread && unreadEqual(currentUnread, unreadInfoToUnread(unreadInfo))) { // Do not update if unread data has not changes @@ -244,6 +260,46 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo }; }, [mx, setUnreadAtom]); + useEffect(() => { + const handleUnreadNotifications = ( + _notification: unknown, + _threadId: string | undefined, + room: Room + ) => { + if (!room || room.isSpaceRoom()) return; + if (room.getMyMembership() !== Membership.Join) return; + + const unreadInfo = getUnreadInfo(room); + if (unreadInfo.total === 0 && unreadInfo.highlight === 0) { + setUnreadAtom({ type: 'DELETE', roomId: room.roomId }); + return; + } + setUnreadAtom({ type: 'PUT', unreadInfo }); + }; + (mx as any).on(RoomEvent.UnreadNotifications, handleUnreadNotifications); + return () => { + (mx as any).removeListener(RoomEvent.UnreadNotifications, handleUnreadNotifications); + }; + }, [mx, setUnreadAtom]); + + useEffect(() => { + const handleRoomAccountData = (mEvent: MatrixEvent, room: Room) => { + if (room.isSpaceRoom()) return; + if (mEvent.getType() !== EventType.FullyRead) return; + + const unreadInfo = getUnreadInfo(room); + if (unreadInfo.total === 0 && unreadInfo.highlight === 0) { + setUnreadAtom({ type: 'DELETE', roomId: room.roomId }); + return; + } + setUnreadAtom({ type: 'PUT', unreadInfo }); + }; + mx.on(RoomEvent.AccountData, handleRoomAccountData); + return () => { + mx.removeListener(RoomEvent.AccountData, handleRoomAccountData); + }; + }, [mx, setUnreadAtom]); + useEffect(() => { setUnreadAtom({ type: 'RESET', diff --git a/src/app/utils/notifications.ts b/src/app/utils/notifications.ts index 4b25a9e8..a6d47b7a 100644 --- a/src/app/utils/notifications.ts +++ b/src/app/utils/notifications.ts @@ -19,6 +19,18 @@ export async function markAsRead(mx: MatrixClient, roomId: string, privateReceip const latestEvent = getLatestValidEvent(); if (latestEvent === null) return; + const latestEventId = latestEvent.getId(); + if (!latestEventId) return; + + // Update both read receipt and fully-read marker so unread state clears reliably + // across clients and bridge-heavy rooms where hidden events may exist. + if (privateReceipt) { + await mx.setRoomReadMarkers(roomId, latestEventId, undefined, latestEvent); + } else { + await mx.setRoomReadMarkers(roomId, latestEventId, latestEvent); + } + + // Keep legacy receipt path as a safety fallback for homeservers with partial support. await mx.sendReadReceipt( latestEvent, privateReceipt ? ReceiptType.ReadPrivate : ReceiptType.Read diff --git a/src/app/utils/room.ts b/src/app/utils/room.ts index a8cb47e2..78db758f 100644 --- a/src/app/utils/room.ts +++ b/src/app/utils/room.ts @@ -212,6 +212,7 @@ export const roomHaveUnread = (mx: MatrixClient, room: Room) => { const userId = mx.getUserId(); if (!userId) return false; const readUpToId = room.getEventReadUpTo(userId); + if (!readUpToId) return false; const liveEvents = room.getLiveTimeline().getEvents(); if (liveEvents[liveEvents.length - 1]?.getSender() === userId) { @@ -224,12 +225,31 @@ export const roomHaveUnread = (mx: MatrixClient, room: Room) => { if (event.getId() === readUpToId) return false; if (isNotificationEvent(event)) return true; } - return true; + return false; }; export const getUnreadInfo = (room: Room): UnreadInfo => { - const total = room.getUnreadNotificationCount(NotificationCountType.Total); + const userId = room.client.getUserId(); + if (userId) { + // Reconcile known notification-count drift (notably with Sliding Sync / mixed receipts). + room.fixupNotifications(userId); + } + + let total = room.getUnreadNotificationCount(NotificationCountType.Total); const highlight = room.getUnreadNotificationCount(NotificationCountType.Highlight); + + // If our latest notification event is confirmed read, clamp stale non-highlight totals. + if (userId && total > 0 && highlight === 0) { + const liveEvents = room.getLiveTimeline().getEvents(); + const latestNotification = [...liveEvents] + .reverse() + .find((event) => !event.isSending() && isNotificationEvent(event)); + const latestNotificationId = latestNotification?.getId(); + if (latestNotificationId && room.hasUserReadEvent(userId, latestNotificationId)) { + total = 0; + } + } + return { roomId: room.roomId, highlight, @@ -244,7 +264,10 @@ export const getUnreadInfos = (mx: MatrixClient): UnreadInfo[] => if (getNotificationType(mx, room.roomId) === NotificationType.Mute) return unread; if (roomHaveNotification(room) || roomHaveUnread(mx, room)) { - unread.push(getUnreadInfo(room)); + const unreadInfo = getUnreadInfo(room); + if (unreadInfo.total > 0 || unreadInfo.highlight > 0) { + unread.push(unreadInfo); + } } return unread; diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index 913cc83b..d4eec8d1 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -68,13 +68,14 @@ const buildDefaultSubscription = (timelineLimit: number): MSC3575RoomSubscriptio const buildLists = ( pageSize: number, timelineLimit: number, - includeInviteList: boolean + includeInviteList: boolean, + requiredState: MSC3575RoomSubscription['required_state'] ): Map => { const lists = new Map(); lists.set(LIST_JOINED, { ranges: [[0, Math.max(0, pageSize - 1)]], timeline_limit: timelineLimit, - required_state: [], + required_state: requiredState, slow_get_all_rooms: true, filters: { is_invite: false, @@ -85,7 +86,7 @@ const buildLists = ( lists.set(LIST_INVITES, { ranges: [[0, Math.max(0, pageSize - 1)]], timeline_limit: timelineLimit, - required_state: [], + required_state: requiredState, slow_get_all_rooms: true, filters: { is_invite: true, @@ -127,7 +128,12 @@ export class SlidingSyncManager { const includeInviteList = config.includeInviteList !== false; const subscription = buildDefaultSubscription(timelineLimit); - const lists = buildLists(listPageSize, timelineLimit, includeInviteList); + const lists = buildLists( + listPageSize, + timelineLimit, + includeInviteList, + subscription.required_state + ); this.listKeys = Array.from(lists.keys()); this.slidingSync = new SlidingSync(proxyBaseUrl, lists, subscription, mx, pollTimeoutMs);