diff --git a/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts b/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts index a681fc5b5..353f77ef9 100644 --- a/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts +++ b/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts @@ -470,20 +470,8 @@ describe('UnifiedPushNotifications', () => { ); }); - it('serializes cross-room summary writes and refreshes from current caches', async () => { + it('posts one notification per room and no account-level summary', async () => { matrixClient.getRoom.mockReturnValue(makeRoom()); - const summaryPosts: Record[] = []; - let releaseFirstSummary!: () => void; - const firstSummary = new Promise((resolve) => { - releaseFirstSummary = resolve; - }); - notificationsApi.sendNotification.mockImplementation(async (notification) => { - if (notification.groupSummary) { - summaryPosts.push(notification); - if (summaryPosts.length === 1) await firstSummary; - } - }); - await listenForUnifiedPushMessages(() => makeSettings() as never); const roomPayload = (roomId: string, eventId: string, roomName: string) => ({ ...encryptedPush(eventId), @@ -491,108 +479,38 @@ describe('UnifiedPushNotifications', () => { room_name: roomName, }); pushHandler({ message: JSON.stringify(roomPayload('!room-a:example.com', '$a', 'Room A')) }); - await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledOnce()); pushHandler({ message: JSON.stringify(roomPayload('!room-b:example.com', '$b', 'Room B')) }); - await vi.waitFor(() => expect(summaryPosts).toHaveLength(1)); - pushHandler({ message: JSON.stringify(roomPayload('!room-c:example.com', '$c', 'Room C')) }); - releaseFirstSummary(); - await vi.waitFor(() => expect(summaryPosts).toHaveLength(2)); - - expect(summaryPosts[0]).toMatchObject({ title: '2 messages in 2 chats' }); - expect(summaryPosts[1]).toMatchObject({ title: '3 messages in 3 chats' }); + await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledTimes(2)); + const posted = notificationsApi.sendNotification.mock.calls.map( + ([notification]) => notification + ); + expect(posted.some((notification) => notification.groupSummary)).toBe(false); + expect(new Set(posted.map((notification) => notification.title))).toEqual( + new Set(['Room A', 'Room B']) + ); + expect(new Set(posted.map((notification) => notification.id)).size).toBe(2); }); - it('compensates a summary that observed a baseline pending for another room', async () => { + it('dismisses a group summary left behind by an older version', async () => { + await listenForUnifiedPushMessages(() => makeSettings() as never); + + await vi.waitFor(() => expect(notificationsApi.removeActive).toHaveBeenCalledOnce()); + expect(notificationsApi.removeActive.mock.calls[0]?.[0]).toEqual([{ id: expect.any(Number) }]); + }); + + it('clears a room even when dismissing its notification fails', async () => { matrixClient.getRoom.mockReturnValue(makeRoom()); - let rejectFailedPost!: (error: Error) => void; - let failedPostStarted!: () => void; - const failedPost = new Promise((_, reject) => { - rejectFailedPost = reject; - }); - const failedPostStartedPromise = new Promise((resolve) => { - failedPostStarted = resolve; - }); - const summaryPosts: Record[] = []; - notificationsApi.sendNotification.mockImplementation(async (notification) => { - const eventId = (notification.extra as Record | undefined)?.event_id; - if (eventId === '$a-failed') { - failedPostStarted(); - await failedPost; - return; - } - if (notification.groupSummary) summaryPosts.push(notification); - }); - await listenForUnifiedPushMessages(() => makeSettings() as never); - const roomPayload = ( - roomId: string, - eventId: string, - roomName: string, - sender_display_name: string - ) => ({ - ...encryptedPush(eventId), - room_id: roomId, - room_name: roomName, - sender_display_name, - }); pushHandler({ - message: JSON.stringify( - roomPayload('!room-a:example.com', '$a-old', 'Room A', 'Old message') - ), + message: JSON.stringify({ ...encryptedPush('$a'), room_id: '!room-a:example.com' }), }); await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledOnce()); - pushHandler({ - message: JSON.stringify( - roomPayload('!room-a:example.com', '$a-failed', 'Room A', 'Failed message') - ), - }); - await failedPostStartedPromise; - pushHandler({ - message: JSON.stringify(roomPayload('!room-b:example.com', '$b', 'Room B', 'B message')), - }); - await vi.waitFor(() => expect(summaryPosts).toHaveLength(1)); - - rejectFailedPost(new Error('pending baseline failed')); - await vi.waitFor(() => expect(summaryPosts).toHaveLength(2)); - - expect(summaryPosts[0]?.inboxLines).toEqual( - expect.arrayContaining(['Room A: Failed message: Encrypted message']) - ); - expect(summaryPosts[1]?.inboxLines).toEqual( - expect.arrayContaining(['Room A: Old message: Encrypted message']) - ); - expect(summaryPosts[1]?.inboxLines).not.toEqual( - expect.arrayContaining(['Room A: Failed message: Encrypted message']) - ); - }); - - it('still cleans up the account summary when child removal fails', async () => { - matrixClient.getRoom.mockReturnValue(makeRoom()); - await listenForUnifiedPushMessages(() => makeSettings() as never); - const roomPayload = (roomId: string, eventId: string) => ({ - ...encryptedPush(eventId), - room_id: roomId, - }); - pushHandler({ message: JSON.stringify(roomPayload('!room-a:example.com', '$a')) }); - pushHandler({ message: JSON.stringify(roomPayload('!room-b:example.com', '$b')) }); - await vi.waitFor(() => - expect( - notificationsApi.sendNotification.mock.calls.some( - ([notification]) => notification.groupSummary - ) - ).toBe(true) - ); - - let removeAttempts = 0; - notificationsApi.removeActive.mockImplementation(async () => { - removeAttempts += 1; - if (removeAttempts === 1) throw new Error('child removal failed'); - }); - await clearRoomNotification('@user:example.com', '!room-a:example.com'); - - expect(removeAttempts).toBe(2); + notificationsApi.removeActive.mockRejectedValueOnce(new Error('child removal failed')); + await expect( + clearRoomNotification('@user:example.com', '!room-a:example.com') + ).resolves.toBeUndefined(); }); it('checks preview policy again after a minimal event resolves', async () => { diff --git a/src/app/features/settings/notifications/UnifiedPushNotifications.ts b/src/app/features/settings/notifications/UnifiedPushNotifications.ts index e316e4eb1..b6506caf4 100644 --- a/src/app/features/settings/notifications/UnifiedPushNotifications.ts +++ b/src/app/features/settings/notifications/UnifiedPushNotifications.ts @@ -438,7 +438,6 @@ type RoomNotifCache = { const roomNotifCaches = new Map(); const roomNotifGenerations = new Map(); const roomNotifQueues = new Map>(); -const accountSummaryQueues = new Map>(); function enqueueRoomOperation(key: string, operation: () => Promise): Promise { const previous = roomNotifQueues.get(key) ?? Promise.resolve(); @@ -454,23 +453,6 @@ function enqueueRoomOperation(key: string, operation: () => Promise): Prom return task; } -function enqueueAccountSummaryOperation( - userId: string, - operation: () => Promise -): Promise { - const previous = accountSummaryQueues.get(userId) ?? Promise.resolve(); - const task = previous.then(operation, operation); - const completion = task.then( - () => undefined, - () => undefined - ); - accountSummaryQueues.set(userId, completion); - void completion.then(() => { - if (accountSummaryQueues.get(userId) === completion) accountSummaryQueues.delete(userId); - }); - return task; -} - function getOrCreateRoomCache(userId: string, roomId: string, roomName: string): RoomNotifCache { const key = `${userId}\u0000${roomId}`; let cache = roomNotifCaches.get(key); @@ -501,71 +483,18 @@ export function resetUnifiedPushNotificationStateForTests(): void { roomNotifCaches.clear(); roomNotifGenerations.clear(); roomNotifQueues.clear(); - accountSummaryQueues.clear(); } -async function refreshAccountSummary( - userId: string, - removeWhenEmpty: boolean, - isCurrent?: () => boolean -): Promise { - await enqueueAccountSummaryOperation(userId, async () => { - let notificationsApi: Awaited>; - try { - notificationsApi = await getTauriNotificationsApi(); - } catch { - return; - } - if (isCurrent && !isCurrent()) return; - - const accountCaches = Array.from(roomNotifCaches.entries()).filter(([key]) => - key.startsWith(`${userId}\u0000`) - ); - const roomCount = accountCaches.length; - if (roomCount <= 1) { - if (removeWhenEmpty) { - try { - await notificationsApi.removeActive([{ id: summaryNotifId(userId) }]); - } catch { - // already dismissed - } - } - return; - } - - const totalMessages = accountCaches - .map(([, accountCache]) => accountCache) - .reduce((sum, accountCache) => sum + accountCache.messages.length, 0); - const summaryText = `${totalMessages} messages in ${roomCount} chats`; - const summaryLines: string[] = []; - accountCaches.forEach(([, accountCache]) => { - const latest = accountCache.messages[accountCache.messages.length - 1]; - if (latest) { - summaryLines.push( - `${accountCache.roomName}: ${latest.sender?.name ?? 'You'}: ${latest.text}` - ); - } - }); - - if (isCurrent && !isCurrent()) return; - try { - await notificationsApi.sendNotification({ - id: summaryNotifId(userId), - title: summaryText, - body: '', - summary: summaryText, - inboxLines: summaryLines.slice(-5), - channelId: MESSAGES_CHANNEL_ID, - group: NOTIF_GROUP_KEY, - groupSummary: true, - icon: 'notification_icon', - silent: true, - autoCancel: true, - }); - } catch { - // The room notification was already posted; a summary is best effort. - } - }); +// Older versions posted an account-level summary that collapsed every room into +// one entry; Android bundles the per-room notifications on its own. +async function dismissLegacyGroupSummary(userId: string): Promise { + if (!userId) return; + try { + const notificationsApi = await getTauriNotificationsApi(); + await notificationsApi.removeActive([{ id: summaryNotifId(userId) }]); + } catch { + // Nothing to dismiss, or the plugin is unavailable. + } } /** Clears accumulated messages for a room and dismisses its notification. */ @@ -580,7 +509,6 @@ export async function clearRoomNotification(userId: string, roomId: string) { } catch { // already dismissed } - await refreshAccountSummary(userId, true); }); } @@ -622,7 +550,6 @@ async function postRoomNotification( inboxLines: inboxLines.length > 1 ? inboxLines : undefined, largeBody: inboxLines.length > 1 ? undefined : latestBody, }); - await refreshAccountSummary(userId, false, isCurrent); return true; } @@ -740,7 +667,6 @@ async function handleRichPushPayload( cache.messages = previousMessages; if (eventId) cache.pendingEventIds.delete(eventId); if (cache.messages.length === 0) roomNotifCaches.delete(cache.key); - await refreshAccountSummary(userId, true); unifiedPushLog.warn('notification', 'UnifiedPush baseline notification failed'); return false; } @@ -990,7 +916,6 @@ async function handleMinimalPushPayload( cache.messages = previousMessages; if (eventId) cache.pendingEventIds.delete(eventId); if (cache.messages.length === 0) roomNotifCaches.delete(cache.key); - await refreshAccountSummary(userId, true); throw error; } @@ -1144,6 +1069,8 @@ export async function listenForUnifiedPushMessages(getSettings: () => Notificati throw error; } + void dismissLegacyGroupSummary(getSettings().mx.getUserId() ?? ''); + return { unregister: async () => { try { diff --git a/src/app/pages/client/client-non-ui/notifications.tsx b/src/app/pages/client/client-non-ui/notifications.tsx index 88419c64d..e20bf9ebb 100644 --- a/src/app/pages/client/client-non-ui/notifications.tsx +++ b/src/app/pages/client/client-non-ui/notifications.tsx @@ -34,6 +34,7 @@ import { settingsAtom } from '$state/settings'; import { nicknamesAtom } from '$state/nicknames'; import { mDirectAtom } from '$state/mDirectList'; import { allInvitesAtom } from '$state/room-list/inviteList'; +import { markAsRead } from '$utils/notifications'; import { usePreviousValue } from '$hooks/usePreviousValue'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { getStateEvent } from '$utils/room/hierarchy'; @@ -740,6 +741,7 @@ const SABLE_REPLY_ACTION = 'sable-reply'; export function NativeNotificationActionRouting() { const mx = useMatrixClient(); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); const queue = useAtomValue(nativeNotificationRepliesAtom); const sessions = useAtomValue(sessionsAtom); const sessionsRef = useRef(sessions); @@ -811,6 +813,9 @@ export function NativeNotificationActionRouting() { setInFlight((previous: Set) => new Set(previous).add(item.key)); void mx .sendMessage(item.roomId, null, { msgtype: MsgType.Text, body: item.text }) + // Replying is reading; otherwise the room stays unread and its + // notification lingers while later pushes stack onto it. + .then(() => markAsRead(mx, item.roomId, hideReads)) .catch(() => { showToast('Reply was not sent. Open the room to retry.'); }) @@ -823,7 +828,7 @@ export function NativeNotificationActionRouting() { remove(item.key); }); return clearExpiryTimer; - }, [mx, queue, remove, setActiveSessionId, inFlight, setInFlight, replyWakeup]); + }, [mx, queue, remove, setActiveSessionId, inFlight, setInFlight, replyWakeup, hideReads]); return null; }