fix: stop wiping unread counts for spaces and unchanged rooms in incremental recompute

This commit is contained in:
Erwan Leboucher committed 2026-07-23 21:24:27 +02:00
1 parent c8ad4d1555
commit 302e9d671d
4 files changed
+217 -5

No files matched your search

+3 -4
View File
@@ -530,10 +530,9 @@ export const getUnreadInfosForRooms = (
deleted.push(roomId);
continue;
}
if (room.isSpaceRoom()) {
deleted.push(roomId);
continue;
}
// Space unread is derived from children in the atom reducer; skip like
// getUnreadInfos rather than deleting.
if (room.isSpaceRoom()) continue;
if (room.getMyMembership() !== 'join') {
deleted.push(roomId);
continue;
+141
View File
@@ -0,0 +1,141 @@
import { describe, expect, it, vi } from 'vitest';
import { EventType, KnownMembership, NotificationCountType } from '$types/matrix-sdk';
import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk';
import { getUnreadInfosForRooms } from './room';
const SPACE = '!space:example.com';
const ROOM_UNREAD = '!unread:example.com';
const ROOM_EMPTY = '!empty:example.com';
const ROOM_MUTED = '!muted:example.com';
const ROOM_LEFT = '!left:example.com';
const MISSING = '!missing:example.com';
const createEvent = (id: string, sender: string, type = 'm.room.message'): MatrixEvent =>
({
getId: () => id,
getSender: () => sender,
getType: () => type,
isRedacted: () => false,
getRelation: () => undefined,
}) as unknown as MatrixEvent;
const createClient = (
rooms: Record<string, Room>,
pushRulesOverride?: unknown[]
): MatrixClient =>
({
getUserId: () => '@user:example.com',
getRoom: (roomId: string) => rooms[roomId],
getRoomPushRule: () => {
throw new Error('no rule');
},
getAccountData: pushRulesOverride
? () => ({ getContent: () => ({ global: { override: pushRulesOverride } }) })
: () => undefined,
}) as unknown as MatrixClient;
const createRoom = (
roomId: string,
opts: {
isSpace?: boolean;
membership?: string;
total?: number;
highlight?: number;
readUpTo?: string | null;
events?: MatrixEvent[];
} = {}
): Room => {
const {
isSpace = false,
membership = KnownMembership.Join,
total = 0,
highlight = 0,
readUpTo = '$read',
events = [],
} = opts;
const client = createClient({ [roomId]: null as unknown as Room });
return {
roomId,
isSpaceRoom: () => isSpace,
getMyMembership: () => membership,
getJoinedMemberCount: () => 10,
getUnreadNotificationCount: vi.fn((type: string) => {
if (type === NotificationCountType.Highlight) return highlight;
return total;
}),
getEventReadUpTo: () => readUpTo,
getLiveTimeline: () => ({ getEvents: () => events }),
getAccountData: () => undefined,
client,
} as unknown as Room;
};
describe('getUnreadInfosForRooms', () => {
it('skips space rooms instead of deleting them', () => {
const unreadRoom = createRoom(ROOM_UNREAD, {
total: 5,
events: [createEvent('$unread', '@other:example.com')],
});
const spaceRoom = createRoom(SPACE, { isSpace: true });
const mx = createClient({ [SPACE]: spaceRoom, [ROOM_UNREAD]: unreadRoom });
(unreadRoom as unknown as { client: MatrixClient }).client = mx;
(spaceRoom as unknown as { client: MatrixClient }).client = mx;
const { unread, deleted } = getUnreadInfosForRooms(mx, [SPACE, ROOM_UNREAD]);
expect(deleted).not.toContain(SPACE);
expect(unread.find((u) => u.roomId === SPACE)).toBeUndefined();
expect(unread.find((u) => u.roomId === ROOM_UNREAD)).toBeDefined();
expect(unread.find((u) => u.roomId === ROOM_UNREAD)?.total).toBe(5);
});
it('does not delete a space even when it is the only dirty room', () => {
const spaceRoom = createRoom(SPACE, { isSpace: true });
const mx = createClient({ [SPACE]: spaceRoom });
(spaceRoom as unknown as { client: MatrixClient }).client = mx;
const { unread, deleted } = getUnreadInfosForRooms(mx, [SPACE]);
expect(deleted).toEqual([]);
expect(unread).toEqual([]);
});
it('deletes rooms that no longer exist', () => {
const mx = createClient({});
const { deleted } = getUnreadInfosForRooms(mx, [MISSING]);
expect(deleted).toContain(MISSING);
});
it('deletes rooms the user has left', () => {
const leftRoom = createRoom(ROOM_LEFT, { membership: KnownMembership.Leave });
const mx = createClient({ [ROOM_LEFT]: leftRoom });
(leftRoom as unknown as { client: MatrixClient }).client = mx;
const { deleted } = getUnreadInfosForRooms(mx, [ROOM_LEFT]);
expect(deleted).toContain(ROOM_LEFT);
});
it('deletes muted rooms', () => {
const mutedRoom = createRoom(ROOM_MUTED);
const mx = createClient(
{ [ROOM_MUTED]: mutedRoom },
[{ rule_id: ROOM_MUTED, actions: ['dont_notify'] }]
);
(mutedRoom as unknown as { client: MatrixClient }).client = mx;
const { deleted } = getUnreadInfosForRooms(mx, [ROOM_MUTED]);
expect(deleted).toContain(ROOM_MUTED);
});
it('deletes rooms whose unread has dropped to zero', () => {
const emptyRoom = createRoom(ROOM_EMPTY, { total: 0, highlight: 0, events: [] });
const mx = createClient({ [ROOM_EMPTY]: emptyRoom });
(emptyRoom as unknown as { client: MatrixClient }).client = mx;
const { unread, deleted } = getUnreadInfosForRooms(mx, [ROOM_EMPTY]);
expect(unread).toHaveLength(0);
expect(deleted).toContain(ROOM_EMPTY);
});
});
+68
View File
@@ -193,6 +193,74 @@ describe('SlidingSyncManager initial request', () => {
]);
});
it('excludes account_data rooms with no events from the dirty set', async () => {
const manager = makeManager(makeMockMx());
const settled = vi.fn<(dirtyRoomIds: ReadonlySet<string>) => void>();
manager.subscribeToResponseSettled(settled);
manager.attach();
fireLifecycle(SlidingSyncState.RequestFinished, {});
fireLifecycle(SlidingSyncState.Complete, {
rooms: {},
extensions: {
account_data: {
rooms: {
'!unchanged:example.com': [],
'!changed:example.com': [
{
type: EventType.FullyRead,
content: { event_id: '$event' },
},
],
},
},
},
});
await Promise.resolve();
expect(settled).toHaveBeenCalledOnce();
expect([...settled.mock.calls[0]![0]]).toEqual(['!changed:example.com']);
});
it('marks only rooms with real data dirty across a full sync response', async () => {
const manager = makeManager(makeMockMx());
const settled = vi.fn<(dirtyRoomIds: ReadonlySet<string>) => void>();
manager.subscribeToResponseSettled(settled);
manager.attach();
fireLifecycle(SlidingSyncState.RequestFinished, {});
fireRoomData('!real:example.com', { initial: false });
fireLifecycle(SlidingSyncState.Complete, {
rooms: {
'!real:example.com': { name: 'Real Room', notification_count: 0, highlight_count: 0 },
},
extensions: {
account_data: {
rooms: Object.fromEntries(
Array.from({ length: 50 }, (_, i) => [`!empty${i}:example.com`, []])
),
},
receipts: {
rooms: {
'!real:example.com': {
type: 'm.receipt',
content: {},
},
},
},
},
});
await Promise.resolve();
expect(settled).toHaveBeenCalledOnce();
const dirty = [...settled.mock.calls[0]![0]];
// Only the room that actually received data — not the 50 empty echoes.
expect(dirty).toEqual(['!real:example.com']);
expect(dirty).toHaveLength(1);
});
it('does not fan out member requests for users referenced by startup sync', async () => {
const getStateEvent = vi.fn<() => Promise<Record<string, unknown>>>().mockResolvedValue({
membership: KnownMembership.Join,
+5 -1
View File
@@ -519,7 +519,11 @@ export class SlidingSyncManager {
const extension = resp.extensions?.[extensionName] as
| RoomScopedExtensionResponse
| undefined;
Object.keys(extension?.rooms ?? {}).forEach((roomId) => this.dirtyRoomIds.add(roomId));
const rooms = extension?.rooms ?? {};
Object.entries(rooms).forEach(([roomId, data]) => {
if (extensionName === 'account_data' && Array.isArray(data) && data.length === 0) return;
this.dirtyRoomIds.add(roomId);
});
});
globalThis.queueMicrotask(() => {