Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions src/app/utils/room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
137 changes: 137 additions & 0 deletions src/app/utils/room.unread.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { describe, expect, it, vi } from 'vitest';
import { 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) => number>((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 changes: 68 additions & 0 deletions src/client/slidingSync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
6 changes: 5 additions & 1 deletion src/client/slidingSync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down
Loading