From cb3d723a8e780fbf791d4cc6861bbe2e1049f415 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sun, 16 Aug 2026 19:08:13 +0200 Subject: [PATCH] fix(unread): clear thread counts on mark as read and honour m.fully_read Closes #956, closes #1813 --- .../fix-thread-and-restart-read-markers.md | 5 + src/app/components/nav/NavMenu.tsx | 2 +- src/app/features/forum/ForumMenu.tsx | 2 +- src/app/features/room/RoomTimeline.tsx | 2 +- src/app/hooks/useRoomMenuActions.ts | 2 +- src/app/pages/client/inbox/Notifications.tsx | 2 +- src/app/pages/client/sidebar/SpaceTabs.tsx | 2 +- src/app/pages/client/space/Space.tsx | 2 +- src/app/utils/notifications.test.ts | 144 ++++++- src/app/utils/notifications.ts | 108 ++++-- src/app/utils/room.unread.test.ts | 147 ++++++- src/app/utils/room/unread.ts | 365 +++++++++--------- 12 files changed, 562 insertions(+), 221 deletions(-) create mode 100644 .changeset/fix-thread-and-restart-read-markers.md diff --git a/.changeset/fix-thread-and-restart-read-markers.md b/.changeset/fix-thread-and-restart-read-markers.md new file mode 100644 index 000000000..0a1011562 --- /dev/null +++ b/.changeset/fix-thread-and-restart-read-markers.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +# Fix rooms staying unread after a thread reply, and after restarting the app diff --git a/src/app/components/nav/NavMenu.tsx b/src/app/components/nav/NavMenu.tsx index 5681e1a22..46db77c37 100644 --- a/src/app/components/nav/NavMenu.tsx +++ b/src/app/components/nav/NavMenu.tsx @@ -23,7 +23,7 @@ export const NavMenu = forwardRef( const handleMarkAsRead = () => { if (!unread) return; - rooms.forEach((rId) => markAsRead(mx, rId, hideReads)); + rooms.forEach((rId) => markAsRead(mx, rId, hideReads, true)); requestClose(); }; diff --git a/src/app/features/forum/ForumMenu.tsx b/src/app/features/forum/ForumMenu.tsx index f47c98cc1..d80a0fd3d 100644 --- a/src/app/features/forum/ForumMenu.tsx +++ b/src/app/features/forum/ForumMenu.tsx @@ -52,7 +52,7 @@ export const ForumMenu = forwardRef( const [invitePrompt, setInvitePrompt] = useState(false); const handleMarkAsRead = () => { - markAsRead(mx, room.roomId, hideReads); + markAsRead(mx, room.roomId, hideReads, true); requestClose(); }; diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index d4387716c..dc4e77048 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -1442,7 +1442,7 @@ export function RoomTimeline({ radii="Pill" outlined before={chipIcon(Checks)} - onClick={() => markAsRead(mx, room.roomId, hideReads)} + onClick={() => markAsRead(mx, room.roomId, hideReads, true)} > Mark as Read diff --git a/src/app/hooks/useRoomMenuActions.ts b/src/app/hooks/useRoomMenuActions.ts index ee47da83c..b904ea0a8 100644 --- a/src/app/hooks/useRoomMenuActions.ts +++ b/src/app/hooks/useRoomMenuActions.ts @@ -49,7 +49,7 @@ export function useRoomMenuActions(room: Room) { ); const handleMarkAsRead = useCallback(() => { - markAsRead(mx, room.roomId, hideReads); + markAsRead(mx, room.roomId, hideReads, true); }, [mx, room.roomId, hideReads]); const handleInvite = useCallback(() => { diff --git a/src/app/pages/client/inbox/Notifications.tsx b/src/app/pages/client/inbox/Notifications.tsx index 8e5ea94b1..d218d118a 100644 --- a/src/app/pages/client/inbox/Notifications.tsx +++ b/src/app/pages/client/inbox/Notifications.tsx @@ -182,7 +182,7 @@ function NotificationRowItem({ variant="Primary" radii="Pill" onClick={() => { - void markAsRead(mx, room.roomId, hideReads) + void markAsRead(mx, room.roomId, hideReads, true) .then(onMarkRead) .catch(() => showToast('Unable to mark this room as read.')); }} diff --git a/src/app/pages/client/sidebar/SpaceTabs.tsx b/src/app/pages/client/sidebar/SpaceTabs.tsx index ffe356f27..d7f3b9ffd 100644 --- a/src/app/pages/client/sidebar/SpaceTabs.tsx +++ b/src/app/pages/client/sidebar/SpaceTabs.tsx @@ -128,7 +128,7 @@ const SpaceMenu = forwardRef( const unread = useRoomsUnread(allChild, roomToUnreadAtom); const handleMarkAsRead = () => { - allChild.forEach((childRoomId) => markAsRead(mx, childRoomId, hideReads)); + allChild.forEach((childRoomId) => markAsRead(mx, childRoomId, hideReads, true)); requestClose(); }; diff --git a/src/app/pages/client/space/Space.tsx b/src/app/pages/client/space/Space.tsx index b947fc8a8..dba1287f0 100644 --- a/src/app/pages/client/space/Space.tsx +++ b/src/app/pages/client/space/Space.tsx @@ -141,7 +141,7 @@ const SpaceMenu = forwardRef(({ room, requestClo const unread = useRoomsUnread(allChild, roomToUnreadAtom); const handleMarkAsRead = () => { - allChild.forEach((childRoomId) => markAsRead(mx, childRoomId, hideReads)); + allChild.forEach((childRoomId) => markAsRead(mx, childRoomId, hideReads, true)); requestClose(); }; diff --git a/src/app/utils/notifications.test.ts b/src/app/utils/notifications.test.ts index c9228b04d..456c3be29 100644 --- a/src/app/utils/notifications.test.ts +++ b/src/app/utils/notifications.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest'; -import type { MatrixClient, MatrixEvent } from '$types/matrix-sdk'; -import { NotificationCountType } from '$types/matrix-sdk'; +import type { MatrixClient, MatrixEvent, Thread } from '$types/matrix-sdk'; +import { NotificationCountType, ReceiptType } from '$types/matrix-sdk'; import { markAsRead } from './notifications'; vi.mock('@tauri-apps/api/core', () => ({ isTauri: () => false })); @@ -14,7 +14,19 @@ const event = (id: string, sending = false): MatrixEvent => isSending: () => sending, }) as unknown as MatrixEvent; -const makeMx = (events: MatrixEvent[], readUpTo: string | null) => { +type ThreadFixture = { + id: string; + replies: MatrixEvent[]; + readUpTo?: string | null; + total?: number; + highlight?: number; +}; + +const makeMx = ( + events: MatrixEvent[], + readUpTo: string | null, + threadFixtures: ThreadFixture[] = [] +) => { const setRoomReadMarkers = vi .fn< ( @@ -25,11 +37,34 @@ const makeMx = (events: MatrixEvent[], readUpTo: string | null) => { ) => Promise >() .mockResolvedValue(); + const sendReadReceipt = vi + .fn<(event: MatrixEvent, receiptType: ReceiptType) => Promise>() + .mockResolvedValue(); const setUnreadNotificationCount = vi.fn<(type: NotificationCountType, count: number) => void>(); + const setThreadUnreadNotificationCount = + vi.fn<(threadId: string, type: NotificationCountType, count: number) => void>(); + + const threads = threadFixtures.map( + (fixture) => + ({ + id: fixture.id, + lastReply: (matches: (ev: MatrixEvent) => boolean) => + fixture.replies.findLast(matches) ?? null, + getEventReadUpTo: () => fixture.readUpTo ?? null, + }) as unknown as Thread + ); + const room = { + roomId, getLiveTimeline: () => ({ getEvents: () => events }), getEventReadUpTo: () => readUpTo, setUnreadNotificationCount, + getThreads: () => threads, + getThreadUnreadNotificationCount: (threadId: string, type: NotificationCountType) => { + const fixture = threadFixtures.find((t) => t.id === threadId); + return (type === NotificationCountType.Highlight ? fixture?.highlight : fixture?.total) ?? 0; + }, + setThreadUnreadNotificationCount, }; return { @@ -37,9 +72,12 @@ const makeMx = (events: MatrixEvent[], readUpTo: string | null) => { getRoom: (id: string) => (id === roomId ? room : null), getUserId: () => userId, setRoomReadMarkers, + sendReadReceipt, } as unknown as MatrixClient, setRoomReadMarkers, + sendReadReceipt, setUnreadNotificationCount, + setThreadUnreadNotificationCount, }; }; @@ -100,4 +138,104 @@ describe('markAsRead', () => { expect(setRoomReadMarkers).not.toHaveBeenCalled(); expect(setUnreadNotificationCount).not.toHaveBeenCalled(); }); + + it('leaves threads alone by default', async () => { + const { mx, sendReadReceipt, setThreadUnreadNotificationCount } = makeMx( + [event('$newest')], + null, + [{ id: '$root', replies: [event('$reply')], total: 1 }] + ); + + await markAsRead(mx, roomId, false); + + expect(sendReadReceipt).not.toHaveBeenCalled(); + expect(setThreadUnreadNotificationCount).not.toHaveBeenCalled(); + }); + + it('clears unread threads when asked, even if the main timeline is already read', async () => { + const { mx, setRoomReadMarkers, sendReadReceipt, setThreadUnreadNotificationCount } = makeMx( + [event('$newest')], + '$newest', + [{ id: '$root', replies: [event('$reply')], total: 1 }] + ); + + await markAsRead(mx, roomId, false, true); + + expect(setRoomReadMarkers).not.toHaveBeenCalled(); + expect(sendReadReceipt).toHaveBeenCalledWith(expect.anything(), ReceiptType.Read); + expect(sendReadReceipt.mock.calls[0]?.[0].getId()).toBe('$reply'); + expect(setThreadUnreadNotificationCount).toHaveBeenCalledWith( + '$root', + NotificationCountType.Total, + 0 + ); + expect(setThreadUnreadNotificationCount).toHaveBeenCalledWith( + '$root', + NotificationCountType.Highlight, + 0 + ); + }); + + it('skips threads that have no unread count', async () => { + const { mx, sendReadReceipt, setThreadUnreadNotificationCount } = makeMx( + [event('$newest')], + '$newest', + [{ id: '$root', replies: [event('$reply')], total: 0, highlight: 0 }] + ); + + await markAsRead(mx, roomId, false, true); + + expect(sendReadReceipt).not.toHaveBeenCalled(); + expect(setThreadUnreadNotificationCount).not.toHaveBeenCalled(); + }); + + it('clears a thread already read up to its last reply without resending a receipt', async () => { + const { mx, sendReadReceipt, setThreadUnreadNotificationCount } = makeMx( + [event('$newest')], + '$newest', + [{ id: '$root', replies: [event('$reply')], readUpTo: '$reply', highlight: 1 }] + ); + + await markAsRead(mx, roomId, false, true); + + expect(sendReadReceipt).not.toHaveBeenCalled(); + expect(setThreadUnreadNotificationCount).toHaveBeenCalledWith( + '$root', + NotificationCountType.Total, + 0 + ); + }); + + it('sends private thread receipts when reads are hidden', async () => { + const { mx, sendReadReceipt } = makeMx([event('$newest')], '$newest', [ + { id: '$root', replies: [event('$reply')], total: 1 }, + ]); + + await markAsRead(mx, roomId, true, true); + + expect(sendReadReceipt).toHaveBeenCalledWith(expect.anything(), ReceiptType.ReadPrivate); + }); + + it('ignores thread replies that are still sending', async () => { + const { mx, sendReadReceipt } = makeMx([event('$newest')], '$newest', [ + { id: '$root', replies: [event('$reply'), event('$local', true)], total: 1 }, + ]); + + await markAsRead(mx, roomId, false, true); + + expect(sendReadReceipt.mock.calls[0]?.[0].getId()).toBe('$reply'); + }); + + it('keeps the thread count when the receipt is rejected', async () => { + const { mx, sendReadReceipt, setThreadUnreadNotificationCount } = makeMx( + [event('$newest')], + '$newest', + [{ id: '$root', replies: [event('$reply')], total: 1 }] + ); + sendReadReceipt.mockRejectedValue(new Error('nope')); + + await markAsRead(mx, roomId, false, true); + + expect(setThreadUnreadNotificationCount).not.toHaveBeenCalled(); + }); }); diff --git a/src/app/utils/notifications.ts b/src/app/utils/notifications.ts index a497ffbe8..a276982ea 100644 --- a/src/app/utils/notifications.ts +++ b/src/app/utils/notifications.ts @@ -1,37 +1,93 @@ -import type { MatrixClient, MatrixEvent } from '$types/matrix-sdk'; -import { NotificationCountType } from '$types/matrix-sdk'; +import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; +import { NotificationCountType, ReceiptType } from '$types/matrix-sdk'; import { isTauri } from '@tauri-apps/api/core'; -export async function markAsRead(mx: MatrixClient, roomId: string, privateReceipt: boolean) { - const room = mx.getRoom(roomId); - if (!room) return; +const latestReceiptTarget = (timeline: MatrixEvent[], readEventId: string | null) => { + for (let i = timeline.length - 1; i >= 0; i -= 1) { + const event = timeline[i]; + if (!event) continue; + if (event.getId() === readEventId) return null; + if (!event.isSending()) return event; + } + return null; +}; - const timeline = room.getLiveTimeline().getEvents(); - const readEventId = room.getEventReadUpTo(mx.getUserId()!); - - const getLatestValidEvent = (): MatrixEvent | null => { - for (let i = timeline.length - 1; i >= 0; i -= 1) { - const latestEvent = timeline[i]; - if (!latestEvent) continue; - if (latestEvent.getId() === readEventId) return null; - if (!latestEvent.isSending()) return latestEvent; - } - return null; - }; - if (timeline.length === 0) return; - const latestEvent = getLatestValidEvent(); - if (latestEvent === null) return; - - const latestEventId = latestEvent.getId(); - if (!latestEventId) return; +const markRoomTimelineAsRead = async ( + mx: MatrixClient, + room: Room, + userId: string, + privateReceipt: boolean +): Promise => { + const target = latestReceiptTarget( + room.getLiveTimeline().getEvents(), + room.getEventReadUpTo(userId) + ); + const targetId = target?.getId(); + if (!target || !targetId) return false; if (privateReceipt) { - await mx.setRoomReadMarkers(roomId, latestEventId, undefined, latestEvent); + await mx.setRoomReadMarkers(room.roomId, targetId, undefined, target); } else { - await mx.setRoomReadMarkers(roomId, latestEventId, latestEvent); + await mx.setRoomReadMarkers(room.roomId, targetId, target); } room.setUnreadNotificationCount(NotificationCountType.Total, 0); room.setUnreadNotificationCount(NotificationCountType.Highlight, 0); + return true; +}; + +// Thread replies never land in the live timeline, and the room badge sums the +// per-thread counters, so the room receipt alone can never clear them. +const markThreadsAsRead = async ( + mx: MatrixClient, + room: Room, + userId: string, + privateReceipt: boolean +): Promise => { + const receiptType = privateReceipt ? ReceiptType.ReadPrivate : ReceiptType.Read; + + const cleared = await Promise.all( + room.getThreads().map(async (thread) => { + const hasUnread = + room.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total) > 0 || + room.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Highlight) > 0; + if (!hasUnread) return false; + + const lastReply = thread.lastReply((event) => !event.isSending()); + const lastReplyId = lastReply?.getId(); + if (!lastReply || !lastReplyId) return false; + + if (thread.getEventReadUpTo(userId) !== lastReplyId) { + try { + await mx.sendReadReceipt(lastReply, receiptType); + } catch { + return false; + } + } + room.setThreadUnreadNotificationCount(thread.id, NotificationCountType.Total, 0); + room.setThreadUnreadNotificationCount(thread.id, NotificationCountType.Highlight, 0); + return true; + }) + ); + + return cleared.some(Boolean); +}; + +// includeThreads is for explicit "mark as read" actions only: reading the main +// timeline must not wipe badges for threads the user has not opened. +export async function markAsRead( + mx: MatrixClient, + roomId: string, + privateReceipt: boolean, + includeThreads = false +) { + const room = mx.getRoom(roomId); + const userId = mx.getUserId(); + if (!room || !userId) return; + + const roomCleared = await markRoomTimelineAsRead(mx, room, userId, privateReceipt); + const threadsCleared = + includeThreads && (await markThreadsAsRead(mx, room, userId, privateReceipt)); + if (!roomCleared && !threadsCleared) return; // On Android (Tauri), dismiss the room's OS notification immediately so // it stays in sync with the read state instead of lingering until the @@ -40,7 +96,7 @@ export async function markAsRead(mx: MatrixClient, roomId: string, privateReceip try { const { clearRoomNotification } = await import('$features/settings/notifications/UnifiedPushNotifications'); - await clearRoomNotification(mx.getUserId() ?? '', roomId); + await clearRoomNotification(userId, roomId); } catch { // Notification plugin not available (desktop, web) — ignore. } diff --git a/src/app/utils/room.unread.test.ts b/src/app/utils/room.unread.test.ts index fefac5994..650635d6f 100644 --- a/src/app/utils/room.unread.test.ts +++ b/src/app/utils/room.unread.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest'; import { KnownMembership, NotificationCountType } from '$types/matrix-sdk'; import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; -import { getUnreadInfo, getUnreadInfosForRooms } from './room/unread'; +import { getUnreadInfo, getUnreadInfosForRooms, isNotificationEvent } from './room/unread'; const SPACE = '!space:example.com'; const ROOM_UNREAD = '!unread:example.com'; @@ -12,13 +12,19 @@ const MISSING = '!missing:example.com'; const ME = '@user:example.com'; const OTHER = '@other:example.com'; -const createEvent = (id: string, sender: string, type = 'm.room.message'): MatrixEvent => +const createEvent = ( + id: string, + sender: string, + type = 'm.room.message', + relation?: { rel_type: string; event_id?: string } +): MatrixEvent => ({ getId: () => id, getSender: () => sender, getType: () => type, isRedacted: () => false, - getRelation: () => undefined, + isSending: () => false, + getRelation: () => relation, }) as unknown as MatrixEvent; const createClient = (rooms: Record, pushRulesOverride?: unknown[]): MatrixClient => @@ -77,7 +83,8 @@ const createRoom = ( getEvents: () => events, getPaginationToken: () => paginationToken, }), - getRoomUnreadNotificationCount: () => total, + getRoomUnreadNotificationCount: (type: string) => + type === NotificationCountType.Highlight ? highlight : total, hasUserReadEvent: () => false, getAccountData: (type: string) => fullyRead && type === 'm.fully_read' @@ -308,6 +315,49 @@ describe('getUnreadInfosForRooms', () => { expect(deleted).toContain(ROOM_UNREAD); }); + // readUpTo is null because the receipt does not survive a restart on some servers. + it('does not badge a room whose fully-read marker covers the loaded timeline', () => { + const room = createRoom(ROOM_UNREAD, { + readUpTo: null, + total: 3, + fullyRead: '$b', + events: [createEvent('$a', OTHER), createEvent('$b', OTHER)], + }); + const mx = bindRoom(room); + + const { unread, deleted } = getUnreadInfosForRooms(mx, [ROOM_UNREAD]); + expect(unread).toHaveLength(0); + expect(deleted).toContain(ROOM_UNREAD); + }); + + it('clamps a stale highlight count when the fully-read marker covers the timeline', () => { + const room = createRoom(ROOM_UNREAD, { + readUpTo: null, + total: 2, + highlight: 2, + fullyRead: '$b', + events: [createEvent('$a', OTHER), createEvent('$b', OTHER)], + }); + const mx = bindRoom(room); + + const { unread, deleted } = getUnreadInfosForRooms(mx, [ROOM_UNREAD]); + expect(unread).toHaveLength(0); + expect(deleted).toContain(ROOM_UNREAD); + }); + + it('still badges when the fully-read marker is behind newer messages', () => { + const room = createRoom(ROOM_UNREAD, { + readUpTo: null, + total: 2, + fullyRead: '$a', + events: [createEvent('$a', OTHER), createEvent('$b', OTHER), createEvent('$c', OTHER)], + }); + const mx = bindRoom(room); + + const { unread } = getUnreadInfosForRooms(mx, [ROOM_UNREAD]); + expect(unread.find((u) => u.roomId === ROOM_UNREAD)?.total).toBe(2); + }); + 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 }); @@ -318,3 +368,92 @@ describe('getUnreadInfosForRooms', () => { expect(deleted).toContain(ROOM_EMPTY); }); }); + +describe('isNotificationEvent', () => { + const room = createRoom(ROOM_UNREAD, { + events: [createEvent('$mine', ME), createEvent('$theirs', OTHER)], + }); + + it('counts messages, encrypted messages and stickers', () => { + expect(isNotificationEvent(createEvent('$a', OTHER, 'm.room.message'))).toBe(true); + expect(isNotificationEvent(createEvent('$a', OTHER, 'm.room.encrypted'))).toBe(true); + expect(isNotificationEvent(createEvent('$a', OTHER, 'm.sticker'))).toBe(true); + }); + + it('ignores membership and other state events', () => { + expect(isNotificationEvent(createEvent('$a', OTHER, 'm.room.member'))).toBe(false); + expect(isNotificationEvent(createEvent('$a', OTHER, 'm.room.topic'))).toBe(false); + expect(isNotificationEvent(createEvent('$a', OTHER, 'm.room.create'))).toBe(false); + }); + + it('ignores edits', () => { + const edit = createEvent('$a', OTHER, 'm.room.message', { + rel_type: 'm.replace', + event_id: '$theirs', + }); + expect(isNotificationEvent(edit, room, ME)).toBe(false); + }); + + it('counts a reaction only when it targets our own message', () => { + const toMine = createEvent('$a', OTHER, 'm.reaction', { + rel_type: 'm.annotation', + event_id: '$mine', + }); + const toTheirs = createEvent('$b', OTHER, 'm.reaction', { + rel_type: 'm.annotation', + event_id: '$theirs', + }); + + expect(isNotificationEvent(toMine, room, ME)).toBe(true); + expect(isNotificationEvent(toTheirs, room, ME)).toBe(false); + }); + + it('ignores a reaction when the target is unknown or there is no context', () => { + const relation = { rel_type: 'm.annotation', event_id: '$gone' }; + expect(isNotificationEvent(createEvent('$a', OTHER, 'm.reaction', relation), room, ME)).toBe( + false + ); + expect(isNotificationEvent(createEvent('$a', OTHER, 'm.reaction', relation))).toBe(false); + expect( + isNotificationEvent( + createEvent('$a', OTHER, 'm.reaction', { rel_type: 'm.annotation' }), + room, + ME + ) + ).toBe(false); + }); + + it('counts a threaded reply like a plain message', () => { + const reply = createEvent('$a', OTHER, 'm.room.message', { + rel_type: 'm.thread', + event_id: '$theirs', + }); + expect(isNotificationEvent(reply, room, ME)).toBe(true); + }); +}); + +describe('getUnreadInfo count sources', () => { + it('keeps the SDK counts for a room with activity but no receipt', () => { + const room = createRoom(ROOM_UNREAD, { + readUpTo: null, + total: 7, + highlight: 2, + events: [createEvent('$a', OTHER)], + }); + bindRoom(room); + + expect(getUnreadInfo(room)).toEqual({ roomId: ROOM_UNREAD, highlight: 2, total: 7 }); + }); + + it('does not recount from the boundary while a highlight count survives', () => { + const room = createRoom(ROOM_UNREAD, { + readUpTo: '$a', + total: 0, + highlight: 4, + events: [createEvent('$a', OTHER), createEvent('$b', OTHER), createEvent('$c', OTHER)], + }); + bindRoom(room); + + expect(getUnreadInfo(room)).toEqual({ roomId: ROOM_UNREAD, highlight: 4, total: 4 }); + }); +}); diff --git a/src/app/utils/room/unread.ts b/src/app/utils/room/unread.ts index b19fa1db6..d56b5e75b 100644 --- a/src/app/utils/room/unread.ts +++ b/src/app/utils/room/unread.ts @@ -37,26 +37,10 @@ export const isDirectInvite = (room: Room | null, myUserId: string | null): bool return content?.is_direct === true; }; -/** - * Detects if a room is a direct message room using multiple signals for robustness: - * 1. Primary: checks if room is in mDirects set (from m.direct account data) - * 2. Fallback: checks if room has exactly 2 joined members (classic DM heuristic) - * - * The fallback handles cases where m.direct account data is incomplete or outdated. - */ export const isDMRoom = (room: Room, mDirects?: Set): boolean => { - // Primary signal: check m.direct account data - if (mDirects?.has(room.roomId)) { - return true; - } - - // Fallback: use member count heuristic for untagged DMs - // Only applies to non-space rooms with exactly 2 members (you + them) - if (!room.isSpaceRoom() && room.getJoinedMemberCount() === 2) { - return true; - } - - return false; + if (mDirects?.has(room.roomId)) return true; + // Fallback for DMs missing from m.direct account data. + return !room.isSpaceRoom() && room.getJoinedMemberCount() === 2; }; const hasNotifyPushAction = (actions: IPushRule['actions']): boolean => @@ -89,44 +73,28 @@ export const getNotificationType = (mx: MatrixClient, roomId: string): Notificat return NotificationType.Default; } - if ((roomPushRule.actions[0] as string) === 'notify') return NotificationType.AllMessages; + if (roomPushRule.actions[0] === PushRuleActionName.Notify) return NotificationType.AllMessages; return NotificationType.MentionsAndKeywords; }; const NOTIFICATION_EVENT_TYPES = new Set([ EventType.RoomMessage, EventType.RoomMessageEncrypted, - EventType.RoomMember, EventType.Sticker, EventType.Reaction, ]); export const isNotificationEvent = (mEvent: MatrixEvent, room?: Room, userId?: string) => { - const eType = mEvent.getType(); - if (!NOTIFICATION_EVENT_TYPES.has(eType)) { - return false; - } - if (eType === 'm.room.member') return false; - + if (!NOTIFICATION_EVENT_TYPES.has(mEvent.getType())) return false; if (mEvent.isRedacted()) return false; + const relation = mEvent.getRelation(); const relationType = relation?.rel_type; + if (relationType === RelationType.Replace) return false; - // Filter out edits - they shouldn't count as new notifications - if (relationType === 'm.replace') return false; - - // For reactions: only count them if they're reactions to the current user's messages if (relationType === RelationType.Annotation) { - if (!room || !userId || !relation) { - // If we don't have room/userId/relation context, filter out all reactions (safe default) - return false; - } - // Get the event being reacted to - const reactedToEventId = relation.event_id; - if (!reactedToEventId) return false; - - const reactedToEvent = room.findEventById(reactedToEventId); - // Only count as notification if the reacted-to message was sent by current user - return reactedToEvent?.getSender() === userId; + // Without context we cannot tell whose message was reacted to, so ignore it. + if (!room || !userId || !relation?.event_id) return false; + return room.findEventById(relation.event_id)?.getSender() === userId; } return true; @@ -139,11 +107,30 @@ export const roomHaveNotification = (room: Room): boolean => { return total > 0 || highlight > 0; }; +export const getFullyReadEventId = (room: Room): string | undefined => + room.getAccountData(EventType.FullyRead)?.getContent<{ event_id?: string }>()?.event_id; + +// m.fully_read is a boundary too: the receipt can be gone after a restart. +export const getReadBoundaryEventId = (room: Room, userId: string): string | undefined => { + const receiptId = room.getEventReadUpTo(userId) ?? undefined; + const fullyReadId = getFullyReadEventId(room); + if (!fullyReadId || receiptId === fullyReadId) return receiptId; + + // Only trust the marker if it is actually loaded. + const liveEvents = room.getLiveTimeline().getEvents(); + for (let i = liveEvents.length - 1; i >= 0; i -= 1) { + const eventId = liveEvents[i]?.getId(); + if (eventId === receiptId) return receiptId; + if (eventId === fullyReadId) return fullyReadId; + } + return receiptId; +}; + export const roomHaveUnread = (mx: MatrixClient, room: Room) => { if (getNotificationType(mx, room.roomId) === NotificationType.Mute) return false; const userId = mx.getUserId(); if (!userId) return false; - const readUpToId = room.getEventReadUpTo(userId); + const readUpToId = getReadBoundaryEventId(room, userId); const liveEvents = room.getLiveTimeline().getEvents(); if (!readUpToId) { @@ -171,9 +158,6 @@ type UnreadInfoOptions = { mDirects?: Set; }; -export const getFullyReadEventId = (room: Room): string | undefined => - room.getAccountData(EventType.FullyRead)?.getContent<{ event_id?: string }>()?.event_id; - export const hasAnyReadReceipt = (room: Room, userId: string): boolean => !!room.getReadReceiptForUserId(userId) || !!room.getReadReceiptForUserId(userId, false, ReceiptType.ReadPrivate); @@ -181,6 +165,23 @@ export const hasAnyReadReceipt = (room: Room, userId: string): boolean => export const isTimelineExhausted = (room: Room): boolean => !room.getLiveTimeline().getPaginationToken(Direction.Backward); +// Accepts m.fully_read as evidence when the receipt is missing or lags behind it. +export const hasReadEvent = (room: Room, userId: string, eventId: string): boolean => { + if (room.hasUserReadEvent(userId, eventId)) return true; + + const fullyReadId = getFullyReadEventId(room); + if (!fullyReadId) return false; + + const liveEvents = room.getLiveTimeline().getEvents(); + for (let i = liveEvents.length - 1; i >= 0; i -= 1) { + const currentId = liveEvents[i]?.getId(); + // Walking backwards, the marker wins only if it sits at or after the event. + if (currentId === fullyReadId) return true; + if (currentId === eventId) return false; + } + return false; +}; + export const isReadBoundaryLoaded = (room: Room, userId: string): boolean => { const readUpToId = room.getEventReadUpTo(userId); if (readUpToId && room.findEventById(readUpToId)) return true; @@ -221,6 +222,111 @@ export const countTimelineUnread = ( return { total, highlight }; }; +type Counts = { total: number; highlight: number }; + +// Clamps only the room portion so thread reply counts survive. +const clampStaleCounts = (room: Room, userId: string, counts: Counts): Counts => { + const roomTotal = room.getRoomUnreadNotificationCount(NotificationCountType.Total); + if (roomTotal === 0) return counts; + + // Own sent events always read as read, which would clamp incorrectly. + const latestNotification = room + .getLiveTimeline() + .getEvents() + .toReversed() + .find( + (event) => + !event.isSending() && + event.getSender() !== userId && + isNotificationEvent(event, room, userId) + ); + const latestNotificationId = latestNotification?.getId(); + if (!latestNotificationId || !hasReadEvent(room, userId, latestNotificationId)) return counts; + + return { + total: counts.total - roomTotal, + highlight: + counts.highlight - room.getRoomUnreadNotificationCount(NotificationCountType.Highlight), + }; +}; + +const countFromBoundary = (room: Room, userId: string): UnreadInfo | undefined => { + const boundaryId = getReadBoundaryEventId(room, userId); + const counted = countTimelineUnread(room, userId, { boundaryEventId: boundaryId }); + if (counted.total === 0) return undefined; + + const countIsExact = + !!(boundaryId && room.findEventById(boundaryId)) || isTimelineExhausted(room); + return { + roomId: room.roomId, + highlight: counted.highlight, + total: counted.total, + estimated: !countIsExact, + }; +}; + +const scanForActivity = ( + room: Room, + userId: string, + fullyReadEventId: string | undefined +): { hasActivity: boolean; foundReadBoundary: boolean } => { + const liveEvents = room.getLiveTimeline().getEvents(); + for (let i = liveEvents.length - 1; i >= 0; i -= 1) { + const event = liveEvents[i]; + if (!event) break; + if (event.getId() === fullyReadEventId || event.getSender() === userId) { + return { hasActivity: false, foundReadBoundary: true }; + } + if (isNotificationEvent(event, room, userId)) { + return { hasActivity: true, foundReadBoundary: false }; + } + } + return { hasActivity: false, foundReadBoundary: false }; +}; + +// Rooms unvisited under sliding sync have no receipt, so SDK counts are unreliable. +const estimateWithoutReceipt = ( + room: Room, + userId: string, + { total, highlight }: Counts +): UnreadInfo | undefined => { + const fullyReadEventId = getFullyReadEventId(room); + const { hasActivity, foundReadBoundary } = scanForActivity(room, userId, fullyReadEventId); + const boundaryKnown = foundReadBoundary || isReadBoundaryLoaded(room, userId); + const hasDistantReadEvidence = + !boundaryKnown && (!!fullyReadEventId || hasAnyReadReceipt(room, userId)); + if (!hasActivity && !hasDistantReadEvidence) return undefined; + + if (total > 0 || highlight > 0) { + return hasActivity ? { roomId: room.roomId, highlight, total } : undefined; + } + + if (boundaryKnown) { + const counted = countTimelineUnread(room, userId, { + boundaryEventId: fullyReadEventId, + stopAtOwnEvent: true, + }); + if (counted.total === 0 && counted.highlight === 0) return undefined; + return { roomId: room.roomId, highlight: counted.highlight, total: counted.total }; + } + if (hasActivity && !fullyReadEventId) { + // No read evidence at all: dot badge with an unknown real count. + return { roomId: room.roomId, highlight: 0, total: 1, estimated: true }; + } + // Cannot prove unread state until the distant boundary is loaded. + return { roomId: room.roomId, highlight: 0, total: 0, estimated: true }; +}; + +// Push rules can fail to match a DM, so unread DMs are badged as highlights regardless. +const shouldForceDMHighlight = (room: Room, mDirects?: Set): boolean => { + if (!isDMRoom(room, mDirects)) return false; + const notificationType = getNotificationType(room.client, room.roomId); + return ( + notificationType !== NotificationType.Mute && + notificationType !== NotificationType.MentionsAndKeywords + ); +}; + const unreadInfoFixupInProgress = new WeakSet(); export const getUnreadInfo = (room: Room, options?: UnreadInfoOptions): UnreadInfo => { @@ -238,131 +344,34 @@ export const getUnreadInfo = (room: Room, options?: UnreadInfoOptions): UnreadIn } } - let total = room.getUnreadNotificationCount(NotificationCountType.Total); - const highlight = room.getUnreadNotificationCount(NotificationCountType.Highlight); - let hasTimelineUnread: boolean | undefined; - const roomHasTimelineUnread = () => { - hasTimelineUnread ??= roomHaveUnread(room.client, room); - return hasTimelineUnread; + let counts: Counts = { + total: room.getUnreadNotificationCount(NotificationCountType.Total), + highlight: room.getUnreadNotificationCount(NotificationCountType.Highlight), }; - // Check if this is a DM and what notification type it has (using multiple signals for robustness) - const isDM = isDMRoom(room, options?.mDirects); - const notificationType = isDM ? getNotificationType(room.client, room.roomId) : undefined; - const shouldForceDMHighlight = - isDM && - notificationType !== NotificationType.Mute && - notificationType !== NotificationType.MentionsAndKeywords; + let cachedTimelineUnread: boolean | undefined; + const hasTimelineUnread = () => { + cachedTimelineUnread ??= roomHaveUnread(room.client, room); + return cachedTimelineUnread; + }; - // If our latest main-timeline notification event is confirmed read, clamp its stale count. - // Only apply to the room (non-thread) portion so thread reply counts are preserved. - // Guard: only clamp when the room has NO receipt-confirmed unread events; if roomHaveUnread - // is true then there genuinely are unread messages and the SDK count is not fully stale. - if (userId && total > 0 && highlight === 0 && !roomHasTimelineUnread()) { - const roomTotal = room.getRoomUnreadNotificationCount(NotificationCountType.Total); - if (roomTotal > 0) { - const liveEvents = room.getLiveTimeline().getEvents(); - // Exclude the user's own messages: own sent events are always "read" (hasUserReadEvent - // returns true for them), which would cause the clamp to fire incorrectly. - const latestNotification = [...liveEvents] - .toReversed() - .find( - (event) => - !event.isSending() && - event.getSender() !== userId && - isNotificationEvent(event, room, userId) - ); - const latestNotificationId = latestNotification?.getId(); - if (latestNotificationId && room.hasUserReadEvent(userId, latestNotificationId)) { - // Subtract only the stale main-timeline count; thread totals remain intact. - total -= roomTotal; - } - } + if (userId && counts.total > 0 && !hasTimelineUnread()) { + counts = clampStaleCounts(room, userId, counts); } - // Fallback: SDK counters are stale/zero but there are receipt-confirmed unread - // messages. Walk the live timeline to compute real counts so the badge number - // and highlight colour reflect actual state rather than a hard-coded stub. - if (total === 0 && highlight === 0 && userId && roomHasTimelineUnread()) { - const readUpToId = room.getEventReadUpTo(userId); - const counted = countTimelineUnread(room, userId, { boundaryEventId: readUpToId }); - if (counted.total > 0) { - const countIsExact = - !!(readUpToId && room.findEventById(readUpToId)) || isTimelineExhausted(room); - return { - roomId: room.roomId, - highlight: counted.highlight, - total: counted.total, - estimated: !countIsExact, - }; - } + if (userId && counts.total === 0 && counts.highlight === 0 && hasTimelineUnread()) { + const counted = countFromBoundary(room, userId); + if (counted) return counted; } - // Sliding sync limitation: unvisited rooms don't have read receipt data, but may have - // timeline activity. Check for notification events from others in the timeline to show a - // badge even when SDK counts are 0 (or unreliable without receipts). - if (userId) { - const readUpToId = room.getEventReadUpTo(userId); - - // If we have no read receipt, SDK counts may be unreliable. Always check timeline. - if (!readUpToId) { - const liveEvents = room.getLiveTimeline().getEvents(); - const fullyReadEventId = getFullyReadEventId(room); - let hasActivity = false; - let foundReadBoundary = false; - for (let i = liveEvents.length - 1; i >= 0; i -= 1) { - const event = liveEvents[i]; - if (!event) break; - if (event.getId() === fullyReadEventId || event.getSender() === userId) { - foundReadBoundary = true; - break; - } - if (isNotificationEvent(event, room, userId)) { - hasActivity = true; - break; - } - } - - const boundaryKnown = foundReadBoundary || isReadBoundaryLoaded(room, userId); - const hasDistantReadEvidence = - !boundaryKnown && (!!fullyReadEventId || hasAnyReadReceipt(room, userId)); - - if (hasActivity || hasDistantReadEvidence) { - if (hasActivity && (total > 0 || highlight > 0)) { - // SDK has counts but no receipt - trust the counts and show them - return { roomId: room.roomId, highlight, total }; - } - if (total === 0 && highlight === 0) { - if (boundaryKnown) { - const counted = countTimelineUnread(room, userId, { - boundaryEventId: fullyReadEventId, - stopAtOwnEvent: true, - }); - if (counted.total > 0 || counted.highlight > 0) { - return { roomId: room.roomId, highlight: counted.highlight, total: counted.total }; - } - } else if (hasActivity && !fullyReadEventId) { - // No read evidence at all: dot badge with an unknown real count. - return { roomId: room.roomId, highlight: 0, total: 1, estimated: true }; - } else { - // Cannot prove unread state until the distant boundary is loaded. - return { roomId: room.roomId, highlight: 0, total: 0, estimated: true }; - } - } - } - } + if (userId && !room.getEventReadUpTo(userId)) { + const estimated = estimateWithoutReceipt(room, userId, counts); + if (estimated) return estimated; } - // For DMs with Default or AllMessages notification type: if there are unread messages, - // ensure we show a notification badge (treat as highlight for badge color purposes). - // This handles cases where push rules don't properly match (e.g., classic sync with - // member_count condition failures, or sliding sync with limited required_state). - if (shouldForceDMHighlight && total > 0 && highlight === 0) { - return { - roomId: room.roomId, - highlight: total, // Treat all unread messages as highlights for DMs - total, - }; + const { total, highlight } = counts; + if (total > 0 && highlight === 0 && shouldForceDMHighlight(room, options?.mDirects)) { + return { roomId: room.roomId, highlight: total, total }; } return { @@ -372,24 +381,22 @@ export const getUnreadInfo = (room: Room, options?: UnreadInfoOptions): UnreadIn }; }; -export const getUnreadInfos = (mx: MatrixClient, options?: UnreadInfoOptions): UnreadInfo[] => { - const unreadInfos = mx.getRooms().reduce((unread, room) => { - if (room.isSpaceRoom()) return unread; - if (room.getMyMembership() !== 'join') return unread; - if (getNotificationType(mx, room.roomId) === NotificationType.Mute) return unread; +const tracksUnread = (mx: MatrixClient, room: Room): boolean => + room.getMyMembership() === 'join' && + getNotificationType(mx, room.roomId) !== NotificationType.Mute; + +const hasUnread = (unreadInfo: UnreadInfo): boolean => + unreadInfo.total > 0 || unreadInfo.highlight > 0; + +export const getUnreadInfos = (mx: MatrixClient, options?: UnreadInfoOptions): UnreadInfo[] => + mx.getRooms().reduce((unread, room) => { + if (room.isSpaceRoom() || !tracksUnread(mx, room)) return unread; - // Always call getUnreadInfo - it has fallback logic for sliding sync rooms without receipts const unreadInfo = getUnreadInfo(room, options); - if (unreadInfo.total > 0 || unreadInfo.highlight > 0) { - unread.push(unreadInfo); - } - + if (hasUnread(unreadInfo)) unread.push(unreadInfo); return unread; }, []); - return unreadInfos; -}; - export const getUnreadInfosForRooms = ( mx: MatrixClient, roomIds: Iterable, @@ -407,17 +414,13 @@ export const getUnreadInfosForRooms = ( // 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; - } - if (getNotificationType(mx, room.roomId) === NotificationType.Mute) { + if (!tracksUnread(mx, room)) { deleted.push(roomId); continue; } const unreadInfo = getUnreadInfo(room, options); - if (unreadInfo.total > 0 || unreadInfo.highlight > 0) { + if (hasUnread(unreadInfo)) { unread.push(unreadInfo); } else { deleted.push(roomId);