Various fixes for UI/Rendering issues in sliding sync

This commit is contained in:
Evie Gauthier committed 2026-03-03 00:05:46 -05:00
1 parent 2aec98afe7
commit 0e076485cd
7 files changed
+280 -9

No files matched your search

@@ -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<string | null>();
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 && (
<Box direction="Column" gap="100">
<Box
direction="Column"
gap="100"
style={{
paddingInline: config.space.S400,
paddingBottom: config.space.S300,
}}
>
<Box justifyContent="SpaceBetween" alignItems="Center">
<Text size="L400">Unread Diagnostics</Text>
<Button
onClick={() =>
copyToClipboard(JSON.stringify(unreadDiagnostics, null, 2))
}
variant="Secondary"
fill="Soft"
size="300"
radii="300"
outlined
>
<Text size="B300">Copy JSON</Text>
</Button>
</Box>
<Text size="T200">
`readUpTo`: {unreadDiagnostics.readUpToEventId ?? 'null'}
</Text>
<Text size="T200">
`m.fully_read`: {unreadDiagnostics.fullyReadEventId ?? 'null'}
</Text>
<Text size="T200">
Latest live: {unreadDiagnostics.latestLiveEventId ?? 'null'} | read?{' '}
{unreadDiagnostics.hasReadLatestLive ? 'yes' : 'no'}
</Text>
<Text size="T200">
Latest notification:{' '}
{unreadDiagnostics.latestNotificationEventId ?? 'null'} | read?{' '}
{unreadDiagnostics.hasReadLatestNotification ? 'yes' : 'no'}
</Text>
<Text size="T200">
SDK unread: {unreadDiagnostics.sdkUnread.total} total /{' '}
{unreadDiagnostics.sdkUnread.highlight} highlight
</Text>
<Text size="T200">
Atom unread:{' '}
{unreadDiagnostics.atomUnread
? `${unreadDiagnostics.atomUnread.total} total / ${unreadDiagnostics.atomUnread.highlight} highlight`
: 'none'}
</Text>
</Box>
<Box justifyContent="SpaceBetween">
<Text size="L400">Events</Text>
<Text size="L400">Total: {roomState.size}</Text>
@@ -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) => {
@@ -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<typeof useMatrixClient>): UnreadDriftRoom[] => {
const userId = mx.getUserId();
if (!userId) return [];
return mx
.getRooms()
.filter((room) => !room.isSpaceRoom() && room.getMyMembership() === Membership.Join)
.reduce<UnreadDriftRoom[]>((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 (
<Box direction="Column" gap="100">
@@ -100,6 +151,14 @@ export function SyncDiagnostics() {
<Text size="T300">
Rooms with more history to paginate: {roomDiagnostics.roomsWithBackPagination}
</Text>
<Text size="T300">Unread drift rooms: {unreadDriftRooms.length}</Text>
{unreadDriftRooms.slice(0, 10).map((room) => (
<Text key={room.roomId} size="T200" priority="300">
{room.roomName}: sdk {room.sdkTotal}/{room.sdkHighlight} | latest{' '}
{room.latestNotificationEventId ?? 'null'} | readUpTo {room.readUpToEventId ?? 'null'}{' '}
| fullyRead {room.fullyReadEventId ?? 'null'}
</Text>
))}
{diagnostics.sliding && (
<>
+56
View File
@@ -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<RoomToUnread, [RoomToUnreadAction], undefin
}
if (action.type === 'PUT') {
const { unreadInfo } = action;
if (unreadInfo.total <= 0 && unreadInfo.highlight <= 0) {
if (get(baseRoomToUnread).has(unreadInfo.roomId)) {
set(
baseRoomToUnread,
produce(get(baseRoomToUnread), (draftRoomToUnread) =>
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',
+12
View File
@@ -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
+26 -3
View File
@@ -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;
+10 -4
View File
@@ -68,13 +68,14 @@ const buildDefaultSubscription = (timelineLimit: number): MSC3575RoomSubscriptio
const buildLists = (
pageSize: number,
timelineLimit: number,
includeInviteList: boolean
includeInviteList: boolean,
requiredState: MSC3575RoomSubscription['required_state']
): Map<string, MSC3575List> => {
const lists = new Map<string, MSC3575List>();
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);