diff --git a/.changeset/local-notification-inbox.md b/.changeset/local-notification-inbox.md index 1371a1e69..e431e8425 100644 --- a/.changeset/local-notification-inbox.md +++ b/.changeset/local-notification-inbox.md @@ -2,4 +2,4 @@ default: minor --- -The notifications inbox is now built from push rules evaluated on this device instead of the server's `/notifications` endpoint, so mentions in encrypted rooms are detected correctly. Notifications can be dismissed individually, the inbox defaults to mentions and DMs, and returning after time away backfills what was missed. +The notifications inbox is now built from push rules evaluated on this device instead of the server's `/notifications` endpoint, so mentions in encrypted rooms are detected correctly. diff --git a/src/app/hooks/useInboxNotificationCount.ts b/src/app/hooks/useInboxNotificationCount.ts index 6a885f5f7..46afbebd9 100644 --- a/src/app/hooks/useInboxNotificationCount.ts +++ b/src/app/hooks/useInboxNotificationCount.ts @@ -4,6 +4,7 @@ import { RoomEvent } from '$types/matrix-sdk'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { getLocalNotificationCache } from '$client/localNotificationCache'; import { isStoredNotificationRead, type StoredNotification } from '$utils/localNotifications'; +import { throttleTrailing, type Throttled } from '$utils/throttleTrailing'; const RECOMPUTE_THROTTLE_MS = 500; @@ -14,14 +15,15 @@ type ReceiptContent = Record>>; class InboxCountStore { private count = 0; private readonly subscribers = new Set<() => void>(); - private trailing: ReturnType | undefined; - private lastRun = 0; + private readonly schedule: Throttled; private detach: (() => void) | undefined; constructor( readonly mx: MatrixClient, private readonly userId: string - ) {} + ) { + this.schedule = throttleTrailing(this.recompute, RECOMPUTE_THROTTLE_MS); + } getSnapshot = (): number => this.count; @@ -35,7 +37,7 @@ class InboxCountStore { }; }; - private counts = (entry: StoredNotification): boolean => { + private isUnreadMention = (entry: StoredNotification): boolean => { if (entry.dismissed) return false; if (!entry.highlight && !entry.isDM) return false; @@ -46,26 +48,12 @@ class InboxCountStore { }; private recompute = (): void => { - this.lastRun = Date.now(); - const next = getLocalNotificationCache(this.userId).countEntries(this.counts); + const next = getLocalNotificationCache(this.userId).countEntries(this.isUnreadMention); if (next === this.count) return; this.count = next; for (const onChange of this.subscribers) onChange(); }; - private schedule = (): void => { - const elapsed = Date.now() - this.lastRun; - if (elapsed >= RECOMPUTE_THROTTLE_MS) { - this.recompute(); - return; - } - if (this.trailing !== undefined) return; - this.trailing = setTimeout(() => { - this.trailing = undefined; - this.recompute(); - }, RECOMPUTE_THROTTLE_MS - elapsed); - }; - private onReceipt: RoomEventHandlerMap[RoomEvent.Receipt] = (event) => { const content = event.getContent(); const readByUs = Object.values(content).some((byType) => @@ -87,10 +75,7 @@ class InboxCountStore { private teardown(): void { this.detach?.(); this.detach = undefined; - if (this.trailing !== undefined) { - clearTimeout(this.trailing); - this.trailing = undefined; - } + this.schedule.cancel(); stores.delete(this.userId); } } diff --git a/src/app/hooks/useLocalNotificationTimeline.ts b/src/app/hooks/useLocalNotificationTimeline.ts index 3eef925e5..53453554b 100644 --- a/src/app/hooks/useLocalNotificationTimeline.ts +++ b/src/app/hooks/useLocalNotificationTimeline.ts @@ -6,6 +6,7 @@ import { allRoomsAtom } from '$state/room-list/roomList'; import { getLocalNotificationCache } from '$client/localNotificationCache'; import { sliceNotificationPage, type StoredNotification } from '$utils/localNotifications'; import { groupNotifications } from '$utils/groupNotifications'; +import { throttleTrailing } from '$utils/throttleTrailing'; type RoomNotificationsGroup = { roomId: string; @@ -18,7 +19,6 @@ type NotificationTimeline = { const RELOAD_THROTTLE_MS = 500; type LoadTimeline = (from?: string) => Promise; -type SilentReloadTimeline = () => Promise; export const sameNotificationTimeline = ( a: NotificationTimeline, @@ -49,7 +49,7 @@ export const useLocalNotificationTimeline = ( paginationLimit: number, filterMode: 'all' | 'mentions' = 'mentions', includeDone?: boolean -): [NotificationTimeline, LoadTimeline, SilentReloadTimeline] => { +): [NotificationTimeline, LoadTimeline] => { const mx = useMatrixClient(); const allRooms = useAtomValue(allRoomsAtom); const allJoinedRooms = useMemo(() => new Set(allRooms), [allRooms]); @@ -96,32 +96,11 @@ export const useLocalNotificationTimeline = ( [applyUpTo, paginationLimit] ); - const silentReloadTimeline: SilentReloadTimeline = useCallback(async () => { - applyUpTo(loadedLimitRef.current); - }, [applyUpTo]); - useEffect(() => { - let trailing: ReturnType | undefined; - let lastRun = 0; - - const run = () => { - lastRun = Date.now(); + const reload = throttleTrailing(() => { applyUpTo(loadedLimitRef.current); bumpReceiptVersion((v) => v + 1); - }; - - const reload = () => { - const elapsed = Date.now() - lastRun; - if (elapsed >= RELOAD_THROTTLE_MS) { - run(); - return; - } - if (trailing !== undefined) return; - trailing = setTimeout(() => { - trailing = undefined; - run(); - }, RELOAD_THROTTLE_MS - elapsed); - }; + }, RELOAD_THROTTLE_MS); const unsubscribe = cache.subscribe(reload); mx.on(RoomEvent.Receipt, reload); @@ -129,9 +108,9 @@ export const useLocalNotificationTimeline = ( return () => { unsubscribe(); mx.off(RoomEvent.Receipt, reload); - clearTimeout(trailing); + reload.cancel(); }; }, [mx, cache, applyUpTo]); - return [notificationTimeline, loadTimeline, silentReloadTimeline]; + return [notificationTimeline, loadTimeline]; }; diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index 2f92e2344..e870e57de 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -6,10 +6,10 @@ import { MatrixRTCSessionProvider } from '$hooks/useMatrixRTCSession'; import { BackgroundNotifications } from './BackgroundNotifications'; import { WebUpdater } from './WebUpdater'; import { NotificationTransportRuntimeFeature } from '$features/settings/notifications/NotificationTransportRuntimeFeature'; +import { NotificationRecorder } from './client-non-ui/notificationRecorder'; import { InviteNotifications, MessageNotifications, - NotificationRecorder, HandleNotificationClick, SyncNotificationSettingsWithServiceWorker, HandleDecryptPushEvent, diff --git a/src/app/pages/client/client-non-ui/notificationRecorder.tsx b/src/app/pages/client/client-non-ui/notificationRecorder.tsx new file mode 100644 index 000000000..a079cb8bf --- /dev/null +++ b/src/app/pages/client/client-non-ui/notificationRecorder.tsx @@ -0,0 +1,192 @@ +import { useAtomValue } from 'jotai'; +import { useEffect, useRef } from 'react'; +import type { MatrixEvent, RoomEventHandlerMap } from '$types/matrix-sdk'; +import { ClientEvent, EventType, RoomEvent, SyncState } from '$types/matrix-sdk'; +import { useMatrixClient } from '$hooks/useMatrixClient'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; +import { mDirectAtom } from '$state/mDirectList'; +import { createLogger } from '$utils/debug'; +import { getNotificationType } from '$utils/room/unread'; +import { + arePushRulesReady, + evaluateNotification, + isAwaitingDecryption, + watchDecryption, +} from '$utils/localNotifications'; +import { getLocalNotificationCache } from '$client/localNotificationCache'; +import { backfillLocalNotifications, runLiveTimelineScan } from '$utils/localNotificationBackfill'; + +const logger = createLogger('NotificationRecorder'); +const RECORDED_CAP = 300; +const HEARTBEAT_INTERVAL_MS = 60_000; + +export function NotificationRecorder() { + const mx = useMatrixClient(); + const mDirects = useAtomValue(mDirectAtom); + const mDirectsRef = useRef(mDirects); + mDirectsRef.current = mDirects; + + const recordedRef = useRef>(new Set()); + const decryptingRef = useRef>(new Set()); + const hasBackfilledRef = useRef(false); + const backfillControllerRef = useRef(undefined); + const decryptWatchersRef = useRef void>>(new Map()); + const hasScannedRef = useRef(false); + const [storeContent] = useSetting(settingsAtom, 'showMessageContentInNotifications'); + const [storeEncryptedContent] = useSetting( + settingsAtom, + 'showMessageContentInEncryptedNotifications' + ); + const storeContentRef = useRef(storeContent); + storeContentRef.current = storeContent; + const storeEncryptedContentRef = useRef(storeContent && storeEncryptedContent); + storeEncryptedContentRef.current = storeContent && storeEncryptedContent; + const prevMxRef = useRef(mx); + if (prevMxRef.current !== mx) { + prevMxRef.current = mx; + recordedRef.current = new Set(); + decryptingRef.current = new Set(); + hasBackfilledRef.current = false; + hasScannedRef.current = false; + } + + useEffect(() => { + const userId = mx.getSafeUserId(); + const cache = getLocalNotificationCache(userId); + const contentOptions = () => ({ + storeContent: storeContentRef.current, + storeEncryptedContent: storeEncryptedContentRef.current, + }); + + const markRecorded = (eventId: string) => { + recordedRef.current.add(eventId); + if (recordedRef.current.size > RECORDED_CAP) { + const oldest = recordedRef.current.values().next().value; + if (oldest !== undefined) recordedRef.current.delete(oldest); + } + }; + + const handler: RoomEventHandlerMap[RoomEvent.Timeline] = ( + mEvent, + room, + toStartOfTimeline, + removed + ) => { + if (toStartOfTimeline || removed) return; + if (!room) return; + const eventId = mEvent.getId(); + if (!eventId) return; + + if (recordedRef.current.has(eventId)) return; + + // Leave unrecorded so the rescan picks it up once push rules arrive. + if (!arePushRulesReady(mx)) return; + + const encrypted = isAwaitingDecryption(mEvent); + if (encrypted && decryptingRef.current.has(eventId)) return; + + const evaluate = () => + evaluateNotification( + mx, + room, + mEvent, + mDirectsRef.current, + getNotificationType(mx, room.roomId), + { storeContent: encrypted ? storeEncryptedContentRef.current : storeContentRef.current } + ); + + markRecorded(eventId); + const stored = evaluate(); + if (stored) cache.merge(stored); + + if (!encrypted) return; + + decryptingRef.current.add(eventId); + decryptWatchersRef.current.set( + mEvent, + watchDecryption( + mEvent, + () => { + decryptingRef.current.delete(eventId); + const upgraded = evaluate(); + if (upgraded) cache.merge(upgraded); + }, + () => decryptingRef.current.delete(eventId) + ) + ); + }; + + mx.on(RoomEvent.Timeline, handler); + + // Only advance the watermark while syncing, so an outage isn't treated as "nothing missed". + const beat = () => { + if (mx.getSyncState() === SyncState.Syncing) cache.updateLastSeenTs(Date.now()); + }; + const heartbeatInterval = setInterval(beat, HEARTBEAT_INTERVAL_MS); + + // SlidingSyncSdk assigns client.pushRules without emitting AccountData, so + // this cannot wait on that event. Runs every start because shouldBackfill + // declines whenever the heartbeat kept the gap under its threshold. + const scanOnce = () => { + if (hasScannedRef.current || !arePushRulesReady(mx)) return; + hasScannedRef.current = true; + void runLiveTimelineScan(mx, userId, mDirectsRef.current, contentOptions()).catch( + (err: unknown) => { + logger.warn('live timeline scan failed', err); + } + ); + }; + + const onSync = (state: SyncState) => { + if ( + state !== SyncState.Prepared && + state !== SyncState.Syncing && + state !== SyncState.Catchup + ) { + return; + } + scanOnce(); + + if (hasBackfilledRef.current) return; + hasBackfilledRef.current = true; + const controller = new AbortController(); + backfillControllerRef.current = controller; + void backfillLocalNotifications( + mx, + userId, + contentOptions(), + Date.now(), + controller.signal + ).catch((err: unknown) => { + logger.warn('backfill failed', err); + }); + }; + mx.on(ClientEvent.Sync, onSync); + const currentState = mx.getSyncState(); + if (currentState) onSync(currentState); + + // Covers a later push-rule change. + const onPushRules = (event: MatrixEvent) => { + if (event.getType() !== (EventType.PushRules as string)) return; + scanOnce(); + }; + mx.on(ClientEvent.AccountData, onPushRules); + + const decryptWatchers = decryptWatchersRef.current; + return () => { + mx.off(RoomEvent.Timeline, handler); + mx.off(ClientEvent.Sync, onSync); + mx.off(ClientEvent.AccountData, onPushRules); + clearInterval(heartbeatInterval); + // These hold mx, room and the previous account's cache through their closure. + for (const stop of decryptWatchers.values()) stop(); + decryptWatchers.clear(); + backfillControllerRef.current?.abort(); + backfillControllerRef.current = undefined; + beat(); + }; + }, [mx]); + + return null; +} diff --git a/src/app/pages/client/client-non-ui/notifications.tsx b/src/app/pages/client/client-non-ui/notifications.tsx index b18bdab55..e3b0b0bb3 100644 --- a/src/app/pages/client/client-non-ui/notifications.tsx +++ b/src/app/pages/client/client-non-ui/notifications.tsx @@ -5,7 +5,6 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import type { RoomEventHandlerMap } from '$types/matrix-sdk'; import { - ClientEvent, MatrixEvent, MatrixEventEvent, MsgType, @@ -57,15 +56,8 @@ import { resolveNotificationPreviewText, } from '$utils/notificationStyle'; import { isMobileOrTablet } from '$utils/platform'; -import { createLogger } from '$utils/debug'; import { createDebugLogger } from '$utils/debugLogger'; import { showToast } from '$state/toast'; -import { arePushRulesReady, evaluateNotification } from '$utils/localNotifications'; -import { getLocalNotificationCache } from '$client/localNotificationCache'; -import { - backfillLocalNotifications, - scheduleLiveTimelineScan, -} from '$utils/localNotificationBackfill'; import { nativeNotificationRepliesAtom, nativeNotificationReplyInFlightAtom, @@ -709,212 +701,6 @@ function registerNativeNotificationListener( }; } -const recorderLogger = createLogger('NotificationRecorder'); -const RECORDED_CAP = 300; -const HEARTBEAT_INTERVAL_MS = 60_000; -const DECRYPT_TIMEOUT_MS = 30_000; - -export function NotificationRecorder() { - const mx = useMatrixClient(); - const mDirects = useAtomValue(mDirectAtom); - const mDirectsRef = useRef(mDirects); - mDirectsRef.current = mDirects; - - const recordedRef = useRef>(new Set()); - const decryptingRef = useRef>(new Set()); - const hasBackfilledRef = useRef(false); - const decryptTimeoutsRef = useRef>>(new Set()); - const backfillControllerRef = useRef(undefined); - const missedBeforePushRulesRef = useRef(false); - const decryptListenersRef = useRef void>>(new Map()); - const hasScannedRef = useRef(false); - const [storeContent] = useSetting(settingsAtom, 'showMessageContentInNotifications'); - const [storeEncryptedContent] = useSetting( - settingsAtom, - 'showMessageContentInEncryptedNotifications' - ); - const storeContentRef = useRef(storeContent); - storeContentRef.current = storeContent; - const storeEncryptedContentRef = useRef(storeContent && storeEncryptedContent); - storeEncryptedContentRef.current = storeContent && storeEncryptedContent; - const prevMxRef = useRef(mx); - if (prevMxRef.current !== mx) { - prevMxRef.current = mx; - recordedRef.current = new Set(); - decryptingRef.current = new Set(); - hasBackfilledRef.current = false; - missedBeforePushRulesRef.current = false; - hasScannedRef.current = false; - } - - useEffect(() => { - const userId = mx.getSafeUserId(); - const cache = getLocalNotificationCache(userId); - - const markRecorded = (eventId: string) => { - recordedRef.current.add(eventId); - if (recordedRef.current.size > RECORDED_CAP) { - const oldest = recordedRef.current.values().next().value; - if (oldest !== undefined) recordedRef.current.delete(oldest); - } - }; - - const handler: RoomEventHandlerMap[RoomEvent.Timeline] = ( - mEvent, - room, - toStartOfTimeline, - removed - ) => { - if (toStartOfTimeline || removed) return; - if (!room) return; - const eventId = mEvent.getId(); - if (!eventId) return; - - if (recordedRef.current.has(eventId)) return; - - // Leave unrecorded so the rescan picks it up once push rules arrive. - if (!arePushRulesReady(mx)) { - missedBeforePushRulesRef.current = true; - return; - } - - if (mEvent.getType() === 'm.room.encrypted' && mEvent.isEncrypted()) { - if (decryptingRef.current.has(eventId)) return; - decryptingRef.current.add(eventId); - markRecorded(eventId); - - const stored = evaluateNotification( - mx, - room, - mEvent, - mDirectsRef.current, - getNotificationType(mx, room.roomId), - { storeContent: storeEncryptedContentRef.current } - ); - if (stored) { - cache.merge(stored); - } - - // Not `once`: Decrypted also fires for a decryption FAILURE, whose clear - // event is an m.bad.encrypted placeholder. Staying subscribed lets the - // SDK's later retry replace it. - const handleDecrypted = () => { - if (mEvent.isDecryptionFailure()) return; - decryptingRef.current.delete(eventId); - const upgraded = evaluateNotification( - mx, - room, - mEvent, - mDirectsRef.current, - getNotificationType(mx, room.roomId), - { storeContent: storeEncryptedContentRef.current } - ); - if (upgraded) cache.merge(upgraded); - mEvent.off(MatrixEventEvent.Decrypted, handleDecrypted); - decryptListenersRef.current.delete(mEvent); - }; - mEvent.on(MatrixEventEvent.Decrypted, handleDecrypted); - decryptListenersRef.current.set(mEvent, handleDecrypted); - - // Stop waiting, but keep the placeholder: a megolm key can still arrive - // later, and deleting the entry loses the notification for good. - const timeoutId = setTimeout(() => { - decryptTimeoutsRef.current.delete(timeoutId); - decryptingRef.current.delete(eventId); - }, DECRYPT_TIMEOUT_MS); - decryptTimeoutsRef.current.add(timeoutId); - return; - } - - const stored = evaluateNotification( - mx, - room, - mEvent, - mDirectsRef.current, - getNotificationType(mx, room.roomId), - { storeContent: storeContentRef.current } - ); - markRecorded(eventId); - if (stored) cache.merge(stored); - }; - - mx.on(RoomEvent.Timeline, handler); - - // Only advance the watermark while syncing, so an outage isn't treated as "nothing missed". - const beat = () => { - if (mx.getSyncState() === SyncState.Syncing) cache.updateLastSeenTs(Date.now()); - }; - const heartbeatInterval = setInterval(beat, HEARTBEAT_INTERVAL_MS); - - // SlidingSyncSdk assigns client.pushRules without emitting AccountData, so - // this cannot wait on that event. Runs every start because shouldBackfill - // declines whenever the heartbeat kept the gap under its threshold. - const scanOnce = () => { - if (hasScannedRef.current || !arePushRulesReady(mx)) return; - hasScannedRef.current = true; - missedBeforePushRulesRef.current = false; - void scheduleLiveTimelineScan(mx, userId, mDirectsRef.current, { - storeContent: storeContentRef.current, - storeEncryptedContent: storeEncryptedContentRef.current, - }).catch((err: unknown) => { - recorderLogger.warn('live timeline scan failed', err); - }); - }; - - const onSync = (state: SyncState) => { - if ( - state !== SyncState.Prepared && - state !== SyncState.Syncing && - state !== SyncState.Catchup - ) { - return; - } - scanOnce(); - - if (hasBackfilledRef.current) return; - hasBackfilledRef.current = true; - const controller = new AbortController(); - backfillControllerRef.current = controller; - void backfillLocalNotifications(mx, userId, Date.now(), controller.signal).catch( - (err: unknown) => { - recorderLogger.warn('backfill failed', err); - } - ); - }; - mx.on(ClientEvent.Sync, onSync); - const currentState = mx.getSyncState(); - if (currentState) onSync(currentState); - - // Covers a later push-rule change. - const onPushRules = (event: MatrixEvent) => { - if (event.getType() !== (EventType.PushRules as string)) return; - scanOnce(); - }; - mx.on(ClientEvent.AccountData, onPushRules); - - const decryptTimeouts = decryptTimeoutsRef.current; - const decryptListeners = decryptListenersRef.current; - return () => { - mx.off(RoomEvent.Timeline, handler); - mx.off(ClientEvent.Sync, onSync); - mx.off(ClientEvent.AccountData, onPushRules); - clearInterval(heartbeatInterval); - for (const id of decryptTimeouts) clearTimeout(id); - decryptTimeouts.clear(); - // These hold mx, room and the previous account's cache through their closure. - for (const [event, listener] of decryptListeners) { - event.off(MatrixEventEvent.Decrypted, listener); - } - decryptListeners.clear(); - backfillControllerRef.current?.abort(); - backfillControllerRef.current = undefined; - beat(); - }; - }, [mx]); - - return null; -} - // Routes taps on native plugin notifications (desktop + iOS) using the `extra` // payload attached in sendNativeTauriNotification. export function NativeNotificationClickRouting() { diff --git a/src/app/pages/client/sidebar/InboxTab.tsx b/src/app/pages/client/sidebar/InboxTab.tsx index aee67e56b..a27c0e46c 100644 --- a/src/app/pages/client/sidebar/InboxTab.tsx +++ b/src/app/pages/client/sidebar/InboxTab.tsx @@ -21,6 +21,7 @@ import { import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; import { useNavToActivePathAtom } from '$state/hooks/navToActivePath'; import { useInviteCount } from '$hooks/useInviteCount'; +import { useInboxNotificationCount } from '$hooks/useInboxNotificationCount'; import { Text, Box, color } from 'folds'; import { EnvelopeSimple, getPhosphorIconSize, Tray } from '$components/icons/phosphor'; import { BookmarkIcon, ChatCircleDotsIcon } from '@phosphor-icons/react'; @@ -32,6 +33,8 @@ export function InboxTab({ isBottom, isMobile }: { isBottom?: boolean; isMobile? const navToActivePath = useAtomValue(useNavToActivePathAtom()); const inboxSelected = useInboxSelected(); const inviteCount = useInviteCount(); + const notificationCount = useInboxNotificationCount(); + const totalBadge = inviteCount + notificationCount; const opened = inboxSelected; const InboxIconSize = getPhosphorIconSize(isBottom ? 'inline' : 'toolbar'); @@ -107,7 +110,7 @@ export function InboxTab({ isBottom, isMobile }: { isBottom?: boolean; isMobile? )} - {inviteCount > 0 && } + {totalBadge > 0 && } ); } diff --git a/src/app/state/utils/atomWithLocalStorage.ts b/src/app/state/utils/atomWithLocalStorage.ts index ceb795e26..f942414e4 100644 --- a/src/app/state/utils/atomWithLocalStorage.ts +++ b/src/app/state/utils/atomWithLocalStorage.ts @@ -1,6 +1,8 @@ import { atom } from 'jotai'; +import { NOTIFICATION_CACHE_KEY_PREFIX } from '$client/localNotificationCache'; +import { SIDEBAR_CACHE_KEY_PREFIX } from '$client/slidingSyncSidebarCache'; -const EVICTABLE_KEY_PREFIXES = ['sable.notificationCache.', 'sable.slidingSyncSidebar.']; +const EVICTABLE_KEY_PREFIXES = [NOTIFICATION_CACHE_KEY_PREFIX, SIDEBAR_CACHE_KEY_PREFIX]; export const getLocalStorageItem = (key: string, defaultValue: T): T => { const item = localStorage.getItem(key); diff --git a/src/app/utils/groupNotifications.ts b/src/app/utils/groupNotifications.ts index 362292e39..28524f16b 100644 --- a/src/app/utils/groupNotifications.ts +++ b/src/app/utils/groupNotifications.ts @@ -1,26 +1,22 @@ import { EventType } from '$types/matrix-sdk'; +import type { StoredNotification } from './localNotifications'; -type NotificationEntry = { - event: { type: string }; - room_id: string; -}; - -type RoomNotificationsGroup = { +type RoomNotificationsGroup = { roomId: string; - notifications: N[]; + notifications: StoredNotification[]; }; -export const groupNotifications = ( - notifications: N[], +export const groupNotifications = ( + notifications: StoredNotification[], allowRooms: Set -): RoomNotificationsGroup[] => { - const groups: RoomNotificationsGroup[] = []; +): RoomNotificationsGroup[] => { + const groups: RoomNotificationsGroup[] = []; notifications.forEach((notification) => { if (notification.event.type === (EventType.RoomMember as string)) return; if (!allowRooms.has(notification.room_id)) return; const groupIndex = groups.length - 1; - const lastAddedGroup: RoomNotificationsGroup | undefined = groups[groupIndex]; + const lastAddedGroup: RoomNotificationsGroup | undefined = groups[groupIndex]; if (notification.room_id === lastAddedGroup?.roomId) { lastAddedGroup.notifications.push(notification); return; diff --git a/src/app/utils/localNotificationBackfill.test.ts b/src/app/utils/localNotificationBackfill.test.ts index 8203aa9e3..24af3c459 100644 --- a/src/app/utils/localNotificationBackfill.test.ts +++ b/src/app/utils/localNotificationBackfill.test.ts @@ -1,18 +1,15 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'; import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; -import { backfillLocalNotifications, scheduleLiveTimelineScan } from './localNotificationBackfill'; +import { backfillLocalNotifications, runLiveTimelineScan } from './localNotificationBackfill'; import { getLocalNotificationCache, clearLocalNotificationCache, } from '$client/localNotificationCache'; import { MAX_BACKFILL_ROOMS } from './localNotifications'; -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - const ROOM_ID = '!active:example.com'; const USER_ID = '@test:example.com'; +const CONTENT = { storeContent: true, storeEncryptedContent: true }; type RoomOverrides = Omit, 'isSpaceRoom'> & { lastActiveTs?: number; @@ -50,17 +47,77 @@ const createEvent = (ts: number, id?: string): Partial => getRelation: () => undefined, }) as unknown as Partial; -// --------------------------------------------------------------------------- -// Setup / teardown -// --------------------------------------------------------------------------- + +type FakeEncryptedEvent = Partial & { + decryptTo: (content: Record) => void; + failDecryption: () => void; +}; + +const createEncryptedEvent = (ts: number, id: string): FakeEncryptedEvent => { + const listeners: (() => void)[] = []; + let type = 'm.room.encrypted'; + let content: Record = { algorithm: 'm.megolm.v1.aes-sha2', ciphertext: 'AAA' }; + let failed = false; + + const event = { + getId: () => id, + getTs: () => ts, + getSender: () => '@other:example.com', + getType: () => type, + getContent: () => content, + isEncrypted: () => true, + isDecryptionFailure: () => failed, + isRedacted: () => false, + isSending: () => false, + getRelation: () => undefined, + on: (_event: string, listener: () => void) => { + listeners.push(listener); + return event; + }, + off: (_event: string, listener: () => void) => { + const index = listeners.indexOf(listener); + if (index !== -1) listeners.splice(index, 1); + return event; + }, + decryptTo: (clear: Record) => { + failed = false; + type = 'm.room.message'; + content = clear; + for (const listener of listeners.slice()) listener(); + }, + failDecryption: () => { + failed = true; + type = 'm.room.message'; + content = { msgtype: 'm.bad.encrypted', body: '** Unable to decrypt **' }; + for (const listener of listeners.slice()) listener(); + }, + }; + + return event as unknown as FakeEncryptedEvent; +}; + +const encryptedClient = (room: Room, notifyFor: (mEvent: MatrixEvent) => boolean): MatrixClient => + ({ + getRooms: () => [room], + getRoom: () => room, + scrollback: async (r: Room) => r, + getAccountData: (type: unknown) => + type === 'm.direct' ? ({ getContent: () => ({}) } as unknown) : undefined, + getRoomPushRule: () => { + throw new Error('no rule'); + }, + getSafeUserId: () => USER_ID, + pushRules: { global: { override: [], content: [], room: [], sender: [], underride: [] } }, + getUserId: () => USER_ID, + pushProcessor: { + actionsForEvent: (mEvent: MatrixEvent) => ({ notify: notifyFor(mEvent), tweaks: {} }), + }, + }) as unknown as MatrixClient; beforeEach(() => { clearLocalNotificationCache(USER_ID); }); -// --------------------------------------------------------------------------- -// Tests -// --------------------------------------------------------------------------- describe('backfillLocalNotifications', () => { it('no watermark (new device) → no backfill', async () => { @@ -84,7 +141,7 @@ describe('backfillLocalNotifications', () => { }, } as unknown as MatrixClient; - const recorded = await backfillLocalNotifications(mx, USER_ID); + const recorded = await backfillLocalNotifications(mx, USER_ID, CONTENT); expect(recorded).toBe(0); expect(scrollback).not.toHaveBeenCalled(); @@ -115,7 +172,7 @@ describe('backfillLocalNotifications', () => { }, } as unknown as MatrixClient; - const recorded = await backfillLocalNotifications(mx, USER_ID, now); + const recorded = await backfillLocalNotifications(mx, USER_ID, CONTENT, now); expect(recorded).toBe(0); expect(scrollback).not.toHaveBeenCalled(); @@ -188,7 +245,7 @@ describe('backfillLocalNotifications', () => { }, } as unknown as MatrixClient; - const recorded = await backfillLocalNotifications(mx, USER_ID, now); + const recorded = await backfillLocalNotifications(mx, USER_ID, CONTENT, now); expect(recorded).toBeGreaterThanOrEqual(0); // Only the active (non-space, non-muted) room should be scrolled @@ -235,7 +292,7 @@ describe('backfillLocalNotifications', () => { }, } as unknown as MatrixClient; - await backfillLocalNotifications(mx, USER_ID, now); + await backfillLocalNotifications(mx, USER_ID, CONTENT, now); // (30 rooms × up to 2 pages = up to 60 calls, but unique rooms ≤ 30.) const scrollbackRoomIds = scrollback.mock.calls.map((call) => (call[0] as Room).roomId); @@ -284,7 +341,7 @@ describe('backfillLocalNotifications', () => { }, } as unknown as MatrixClient; - await backfillLocalNotifications(mx, USER_ID, now); + await backfillLocalNotifications(mx, USER_ID, CONTENT, now); expect(scrollback).toHaveBeenCalledTimes(1); }); @@ -329,7 +386,7 @@ describe('backfillLocalNotifications', () => { }, } as unknown as MatrixClient; - await backfillLocalNotifications(mx, uid, now); + await backfillLocalNotifications(mx, uid, CONTENT, now); expect(scrollback).toHaveBeenCalledTimes(1); clearLocalNotificationCache(uid); } @@ -369,7 +426,7 @@ describe('backfillLocalNotifications', () => { }, } as unknown as MatrixClient; - await backfillLocalNotifications(mx, uid, now); + await backfillLocalNotifications(mx, uid, CONTENT, now); expect(scrollback).toHaveBeenCalledTimes(2); clearLocalNotificationCache(uid); } @@ -420,7 +477,7 @@ describe('backfillLocalNotifications', () => { }, } as unknown as MatrixClient; - await backfillLocalNotifications(mx, USER_ID, now); + await backfillLocalNotifications(mx, USER_ID, CONTENT, now); expect(scrollback).not.toHaveBeenCalled(); }); @@ -469,7 +526,7 @@ describe('backfillLocalNotifications', () => { }, } as unknown as MatrixClient; - await backfillLocalNotifications(mx, USER_ID, now); + await backfillLocalNotifications(mx, USER_ID, CONTENT, now); expect(maxInFlight).toBe(1); }); @@ -515,7 +572,7 @@ describe('backfillLocalNotifications', () => { }, } as unknown as MatrixClient; - const recorded = await backfillLocalNotifications(mx, USER_ID, now); + const recorded = await backfillLocalNotifications(mx, USER_ID, CONTENT, now); expect(recorded).toBe(3); }); @@ -561,19 +618,87 @@ describe('backfillLocalNotifications', () => { }, } as unknown as MatrixClient; - const recorded = await backfillLocalNotifications(mx, USER_ID, now); + const recorded = await backfillLocalNotifications(mx, USER_ID, CONTENT, now); expect(recorded).toBe(1); }); }); -// --------------------------------------------------------------------------- -// recordLiveTimelines — recovers what was dropped before push rules synced -// --------------------------------------------------------------------------- -describe('scheduleLiveTimelineScan', () => { - const CONTENT = { storeContent: true, storeEncryptedContent: true }; +describe('backfillLocalNotifications in encrypted rooms', () => { + const encryptedRoom = (events: Partial[], now: number): Room => + createRoom(ROOM_ID, { + lastActiveTs: now - 5 * 1000, + _events: events, + getLiveTimeline: () => + ({ + getEvents: () => events as MatrixEvent[], + getState: () => ({ getStateEvents: () => ({}) }), + }) as unknown as ReturnType, + }); + it('records a mention that only becomes visible after decryption', async () => { + const now = Date.now(); + getLocalNotificationCache(USER_ID).updateLastSeenTs(now - 2 * 60 * 60 * 1000); + + const mEvent = createEncryptedEvent(now - 10 * 1000, '$enc'); + const room = encryptedRoom([mEvent], now); + // Ciphertext matches no rule; the mention only shows once decrypted. + const mx = encryptedClient(room, (e) => e.getType() === 'm.room.message'); + + const recorded = await backfillLocalNotifications(mx, USER_ID, CONTENT, now); + expect(recorded).toBe(0); + + mEvent.decryptTo({ msgtype: 'm.text', body: 'hey @test' }); + + const entries = getLocalNotificationCache(USER_ID).getEntries(); + expect(entries).toHaveLength(1); + expect(entries[0]!.event.content.body).toBe('hey @test'); + }); + + it('keeps the placeholder when decryption fails', async () => { + const now = Date.now(); + getLocalNotificationCache(USER_ID).updateLastSeenTs(now - 2 * 60 * 60 * 1000); + + const mEvent = createEncryptedEvent(now - 10 * 1000, '$enc'); + const room = encryptedRoom([mEvent], now); + const mx = encryptedClient(room, () => true); + + await backfillLocalNotifications(mx, USER_ID, CONTENT, now); + expect(getLocalNotificationCache(USER_ID).getEntries()).toHaveLength(1); + + mEvent.failDecryption(); + expect(getLocalNotificationCache(USER_ID).getEntries()).toHaveLength(1); + + // The SDK retries once the megolm key arrives. + mEvent.decryptTo({ msgtype: 'm.text', body: 'recovered' }); + const entries = getLocalNotificationCache(USER_ID).getEntries(); + expect(entries).toHaveLength(1); + expect(entries[0]!.event.content.body).toBe('recovered'); + }); + + it('omits the body when encrypted content must not be persisted', async () => { + const now = Date.now(); + getLocalNotificationCache(USER_ID).updateLastSeenTs(now - 2 * 60 * 60 * 1000); + + const mEvent = createEvent(now - 10 * 1000, '$clear'); + const room = encryptedRoom([mEvent], now); + const mx = encryptedClient(room, () => true); + + await backfillLocalNotifications( + mx, + USER_ID, + { storeContent: true, storeEncryptedContent: false }, + now + ); + + const entry = getLocalNotificationCache(USER_ID).getEntries()[0]!; + expect(entry.event.content.body).toBeUndefined(); + expect(entry.event.content.msgtype).toBe('m.text'); + }); +}); + +describe('runLiveTimelineScan', () => { const clientWith = (rooms: Room[], withPushRules = true): MatrixClient => ({ getRooms: () => rooms, @@ -597,7 +722,7 @@ describe('scheduleLiveTimelineScan', () => { _events: [createEvent(1000, '$a'), createEvent(2000, '$b')], }); - const recorded = await scheduleLiveTimelineScan( + const recorded = await runLiveTimelineScan( clientWith([room]), USER_ID, new Set(), @@ -612,8 +737,8 @@ describe('scheduleLiveTimelineScan', () => { const room = createRoom(ROOM_ID, { _events: [createEvent(1000, '$a')] }); const mx = clientWith([room]); - await scheduleLiveTimelineScan(mx, USER_ID, new Set(), CONTENT); - await scheduleLiveTimelineScan(mx, USER_ID, new Set(), CONTENT); + await runLiveTimelineScan(mx, USER_ID, new Set(), CONTENT); + await runLiveTimelineScan(mx, USER_ID, new Set(), CONTENT); expect(getLocalNotificationCache(USER_ID).getEntries()).toHaveLength(1); }); @@ -623,9 +748,9 @@ describe('scheduleLiveTimelineScan', () => { const mx = clientWith([room]); const cache = getLocalNotificationCache(USER_ID); - await scheduleLiveTimelineScan(mx, USER_ID, new Set(), CONTENT); + await runLiveTimelineScan(mx, USER_ID, new Set(), CONTENT); cache.dismiss('$a'); - await scheduleLiveTimelineScan(mx, USER_ID, new Set(), CONTENT); + await runLiveTimelineScan(mx, USER_ID, new Set(), CONTENT); expect(cache.getEntries()[0]!.dismissed).toBe(true); }); @@ -633,7 +758,7 @@ describe('scheduleLiveTimelineScan', () => { it('records nothing while push rules are still missing', async () => { const room = createRoom(ROOM_ID, { _events: [createEvent(1000, '$a')] }); - const recorded = await scheduleLiveTimelineScan( + const recorded = await runLiveTimelineScan( clientWith([room], false), USER_ID, new Set(), @@ -649,15 +774,13 @@ describe('scheduleLiveTimelineScan', () => { _events: [createEvent(1000, '$a')], }); - expect(await scheduleLiveTimelineScan(clientWith([space]), USER_ID, new Set(), CONTENT)).toBe( - 0 - ); + expect(await runLiveTimelineScan(clientWith([space]), USER_ID, new Set(), CONTENT)).toBe(0); }); it('omits the body when content must not be persisted', async () => { const room = createRoom(ROOM_ID, { _events: [createEvent(1000, '$a')] }); - await scheduleLiveTimelineScan(clientWith([room]), USER_ID, new Set(), { + await runLiveTimelineScan(clientWith([room]), USER_ID, new Set(), { storeContent: false, storeEncryptedContent: false, }); diff --git a/src/app/utils/localNotificationBackfill.ts b/src/app/utils/localNotificationBackfill.ts index c7bb2e821..164fc568f 100644 --- a/src/app/utils/localNotificationBackfill.ts +++ b/src/app/utils/localNotificationBackfill.ts @@ -1,14 +1,16 @@ import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; -import { ClientEvent, Direction, EventType, MatrixEventEvent } from '$types/matrix-sdk'; +import { ClientEvent, EventType } from '$types/matrix-sdk'; import { NotificationType } from '$types/matrix/room'; import { getLocalNotificationCache } from '$client/localNotificationCache'; import { createLogger } from '$utils/debug'; -import { getAccountData } from '$utils/room/hierarchy'; +import { getAccountData, getStateEvent } from '$utils/room/hierarchy'; import { getMDirects, getNotificationType } from '$utils/room/unread'; import { evaluateNotification, + isAwaitingDecryption, selectBackfillRooms, shouldBackfill, + watchDecryption, backfillPageCount, type BackfillRoomInfo, type StoredNotification, @@ -17,7 +19,6 @@ import { const logger = createLogger('localNotificationBackfill'); const SCROLLBACK_LIMIT = 50; -const DECRYPT_TIMEOUT_MS = 30_000; // Bounds the transient batch; the cache only keeps MAX_ENTRIES anyway. const SCAN_FLUSH_BATCH = 200; @@ -27,15 +28,9 @@ export type ScanContentOptions = { }; const isEncryptedRoom = (room: Room): boolean => - room - .getLiveTimeline() - .getState(Direction.Forward) - ?.getStateEvents(EventType.RoomEncryption, '') !== null; + getStateEvent(room, EventType.RoomEncryption) !== undefined; -// Recovers events that arrived before push rules synced. Reads only what the -// client already holds — no network — and yields between rooms so a large -// account cannot block the main thread through a whole scan. -export const scheduleLiveTimelineScan = async ( +export const runLiveTimelineScan = async ( mx: MatrixClient, userId: string, mDirects: Set, @@ -81,6 +76,7 @@ export const scheduleLiveTimelineScan = async ( export const backfillLocalNotifications = async ( mx: MatrixClient, userId: string, + content: ScanContentOptions, now: number = Date.now(), signal?: AbortSignal ): Promise => { @@ -94,7 +90,6 @@ export const backfillLocalNotifications = async ( return 0; } - // Build BackfillRoomInfo from all rooms the client knows about. const allRooms = mx.getRooms(); const roomInfos: BackfillRoomInfo[] = allRooms.map((room) => ({ roomId: room.roomId, @@ -104,9 +99,13 @@ export const backfillLocalNotifications = async ( })); const selectedRoomIds = selectBackfillRooms(roomInfos, watermark); const pages = backfillPageCount(watermark, now); + const activeRooms = roomInfos.filter( + (r) => !r.isSpaceRoom && !r.isMuted && r.lastActiveTs > watermark + ).length; logger.log('backfill starting', { rooms: selectedRoomIds.length, + skippedRooms: activeRooms - selectedRoomIds.length, pages, gapMs: now - watermark, }); @@ -134,12 +133,22 @@ export const backfillLocalNotifications = async ( let recorded = 0; const processed = new Set(); + const stopWatchers: (() => void)[] = []; + const releaseWatchers = () => { + for (const stop of stopWatchers) stop(); + stopWatchers.length = 0; + }; + signal?.addEventListener('abort', releaseWatchers, { once: true }); + for (const roomId of selectedRoomIds) { if (signal?.aborted) return recorded; const room = mx.getRoom(roomId); if (!room) continue; const notificationType = getNotificationType(mx, roomId); if (notificationType === NotificationType.Mute) continue; + const storeContent = isEncryptedRoom(room) + ? content.storeEncryptedContent + : content.storeContent; try { for (let page = 0; page < pages; page += 1) { @@ -154,33 +163,24 @@ export const backfillLocalNotifications = async ( const eventId = mEvent.getId(); if (!eventId || processed.has(eventId)) continue; processed.add(eventId); - const stored = evaluateNotification(mx, room, mEvent, mDirects, notificationType); + const evaluate = () => + evaluateNotification(mx, room, mEvent, mDirects, notificationType, { storeContent }); + + const stored = evaluate(); if (stored) { cache.merge(stored); recorded += 1; - if (mEvent.getType() === 'm.room.encrypted' && mEvent.isEncrypted()) { - const handleDecrypted = () => { - const upgraded = evaluateNotification(mx, room, mEvent, mDirects, notificationType); + } + + // Also watch events that did not notify as ciphertext: a mention is + // only visible once the clear event arrives. + if (isAwaitingDecryption(mEvent)) { + stopWatchers.push( + watchDecryption(mEvent, () => { + const upgraded = evaluate(); if (upgraded) cache.merge(upgraded); - else cache.remove(eventId); - }; - mEvent.once(MatrixEventEvent.Decrypted, handleDecrypted); - const timeoutId = setTimeout(() => { - mEvent.off(MatrixEventEvent.Decrypted, handleDecrypted); - }, DECRYPT_TIMEOUT_MS); - if (signal) { - if (signal.aborted) mEvent.off(MatrixEventEvent.Decrypted, handleDecrypted); - else - signal.addEventListener( - 'abort', - () => { - clearTimeout(timeoutId); - mEvent.off(MatrixEventEvent.Decrypted, handleDecrypted); - }, - { once: true } - ); - } - } + }) + ); } } diff --git a/src/app/utils/localNotifications.test.ts b/src/app/utils/localNotifications.test.ts index d4cdd37d7..6eaf31b6e 100644 --- a/src/app/utils/localNotifications.test.ts +++ b/src/app/utils/localNotifications.test.ts @@ -17,9 +17,6 @@ const USER_ID = '@user:example.com'; const OTHER_USER = '@other:example.com'; const EVENT_ID = '$event1'; -// --------------------------------------------------------------------------- -// Mock helpers — follow the hand-rolled pattern from room.unread.test.ts -// --------------------------------------------------------------------------- const createEvent = (overrides: Partial = {}): MatrixEvent => ({ @@ -71,9 +68,6 @@ const createClient = ( }, }) as unknown as MatrixClient; -// --------------------------------------------------------------------------- -// evaluateNotification exclusions -// --------------------------------------------------------------------------- describe('arePushRulesReady', () => { it('is false before push rules have synced', () => { @@ -218,9 +212,6 @@ describe('evaluateNotification exclusions', () => { }); }); -// --------------------------------------------------------------------------- -// evaluateNotification inclusions -// --------------------------------------------------------------------------- describe('evaluateNotification inclusions', () => { it('returns StoredNotification for normal message with notify=true', () => { @@ -349,9 +340,6 @@ describe('evaluateNotification inclusions', () => { }); }); -// --------------------------------------------------------------------------- -// sliceNotificationPage -// --------------------------------------------------------------------------- describe('sliceNotificationPage', () => { const makeItem = ( @@ -449,10 +437,6 @@ describe('sliceNotificationPage', () => { }); }); -// --------------------------------------------------------------------------- -// isStoredNotificationRead -// --------------------------------------------------------------------------- - describe('isStoredNotificationRead', () => { const entry = (ts = 1000): StoredNotification => ({ room_id: ROOM_ID, event: { event_id: EVENT_ID }, ts }) as StoredNotification; @@ -497,8 +481,6 @@ describe('isStoredNotificationRead', () => { expect(isStoredNotificationRead(room, USER_ID, entry(9000))).toBe(false); }); - // Under sliding sync an entry outside the loaded window is the normal case, - // so it must not be hidden just because nothing resolves. it('treats an unresolvable entry as unread', () => { const room = readStateRoom({}); diff --git a/src/app/utils/localNotifications.ts b/src/app/utils/localNotifications.ts index 7aa006284..aea8c78eb 100644 --- a/src/app/utils/localNotifications.ts +++ b/src/app/utils/localNotifications.ts @@ -1,5 +1,6 @@ + import type { IContent, IEvent, MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; -import { ReceiptType } from '$types/matrix-sdk'; +import { EventType, MatrixEventEvent, ReceiptType } from '$types/matrix-sdk'; import { NotificationType } from '$types/matrix/room'; import { isDMRoom, isNotificationEvent } from './room/unread'; @@ -14,9 +15,6 @@ export type StoredNotification = { export const MAX_BODY_LENGTH = 120; -// HTML cannot be sliced without breaking tags, so oversized messages lose it. -// Ciphertext is dropped: multi-KB, shares the session's localStorage budget, and -// is never rendered. Always copies — the SDK mutates `content` in place. const truncateContent = (content: IContent, storeContent: boolean): IContent => { if (content.ciphertext !== undefined) { return typeof content.algorithm === 'string' ? { algorithm: content.algorithm } : {}; @@ -42,8 +40,6 @@ const truncateContent = (content: IContent, storeContent: boolean): IContent => return truncated; }; -// Defaults to public receipts only, and markAsRead sends a private one when -// hideReads is on. const latestReceiptTs = (room: Room, userId: string): number | undefined => { const timestamps = [ReceiptType.Read, ReceiptType.ReadPrivate] .map((type) => room.getReadReceiptForUserId(userId, false, type)?.data?.ts) @@ -57,26 +53,17 @@ export const isStoredNotificationRead = ( userId: string, entry: StoredNotification ): boolean => { - // hasUserReadEvent warns for events missing from the timeline, so only - // consult it while the event is known. if (room.findEventById(entry.event.event_id)) { return room.hasUserReadEvent(userId, entry.event.event_id); } - // Outside the loaded window, which under sliding sync is routine. Compare - // against the receipt timestamp and default to UNREAD, so a notification is - // never hidden just because its event is not in memory. const receiptTs = latestReceiptTs(room, userId); if (receiptTs === undefined) return false; return entry.ts <= receiptTs; }; -// actionsForEvent returns {} rather than throwing before push rules sync, which -// reads as "do not notify". export const arePushRulesReady = (mx: MatrixClient): boolean => mx.pushRules?.global !== undefined; -// The DM override below force-notifies anything in a DM. These types are -// explicitly dont_notify by push rule and must not be resurrected by it. const DM_OVERRIDE_EXCLUDED = new Set(['m.reaction', 'm.room.create']); export type EvaluateOptions = { @@ -152,6 +139,29 @@ export const evaluateNotification = ( }; }; +export const DECRYPT_WAIT_MS = 30_000; + +export const isAwaitingDecryption = (mEvent: MatrixEvent): boolean => + mEvent.getType() === (EventType.RoomMessageEncrypted as string) && mEvent.isEncrypted(); + +export const watchDecryption = ( + mEvent: MatrixEvent, + onDecrypted: () => void, + onGiveUp?: () => void +): (() => void) => { + const listener = () => { + if (mEvent.isDecryptionFailure()) return; + onDecrypted(); + }; + mEvent.on(MatrixEventEvent.Decrypted, listener); + const giveUpId = onGiveUp && setTimeout(onGiveUp, DECRYPT_WAIT_MS); + + return () => { + if (giveUpId !== undefined) clearTimeout(giveUpId); + mEvent.off(MatrixEventEvent.Decrypted, listener); + }; +}; + export const sliceNotificationPage = ( all: StoredNotification[], offset: number, @@ -169,9 +179,6 @@ export const sliceNotificationPage = ( return { page, nextToken }; }; -// --------------------------------------------------------------------------- -// Gap backfill — pure decision logic. Testable without network. -// --------------------------------------------------------------------------- export const GAP_THRESHOLD_MS = 5 * 60 * 1000; export const MAX_BACKFILL_ROOMS = 30; diff --git a/src/app/utils/throttleTrailing.ts b/src/app/utils/throttleTrailing.ts new file mode 100644 index 000000000..fde113684 --- /dev/null +++ b/src/app/utils/throttleTrailing.ts @@ -0,0 +1,32 @@ +export type Throttled = (() => void) & { cancel: () => void }; + +/** Runs immediately when idle, otherwise once more at the end of the window. */ +export const throttleTrailing = (fn: () => void, waitMs: number): Throttled => { + let trailing: ReturnType | undefined; + let lastRun = 0; + + const run = () => { + lastRun = Date.now(); + fn(); + }; + + const throttled = () => { + const elapsed = Date.now() - lastRun; + if (elapsed >= waitMs) { + run(); + return; + } + if (trailing !== undefined) return; + trailing = setTimeout(() => { + trailing = undefined; + run(); + }, waitMs - elapsed); + }; + + throttled.cancel = () => { + clearTimeout(trailing); + trailing = undefined; + }; + + return throttled; +}; diff --git a/src/client/localNotificationCache.test.ts b/src/client/localNotificationCache.test.ts index bd8c1a05e..2e1dc85d4 100644 --- a/src/client/localNotificationCache.test.ts +++ b/src/client/localNotificationCache.test.ts @@ -28,11 +28,6 @@ const makeEntry = ( dismissed, }); -/** - * Every cache instance registers a `storage` listener and can hold a pending - * debounced write, both of which would bleed into later tests under the same - * storage key. Track them and tear them down. - */ const caches: LocalNotificationCache[] = []; const openCache = (id: string): LocalNotificationCache => { const cache = new LocalNotificationCache(id); @@ -256,10 +251,6 @@ describe('LocalNotificationCache', () => { }); }); -// --------------------------------------------------------------------------- -// mergeMany / countEntries — a batched scan must not notify per entry -// --------------------------------------------------------------------------- - describe('LocalNotificationCache batching', () => { it('notifies once for a whole batch', () => { const cache = openCache(userId); diff --git a/src/client/localNotificationCache.ts b/src/client/localNotificationCache.ts index 4cf858df2..23ed57ef9 100644 --- a/src/client/localNotificationCache.ts +++ b/src/client/localNotificationCache.ts @@ -1,5 +1,7 @@ import type { StoredNotification } from '$utils/localNotifications'; +export const NOTIFICATION_CACHE_KEY_PREFIX = 'sable.notificationCache.'; + const CACHE_VERSION = 1; const MAX_ENTRIES = 300; const CACHE_WRITE_DELAY_MS = 500; @@ -12,6 +14,9 @@ type CacheData = { lastSeenTs?: number; }; +const storageKeyFor = (userId: string): string => + `${NOTIFICATION_CACHE_KEY_PREFIX}v${CACHE_VERSION}.${encodeURIComponent(userId)}`; + const emptyCache = (): CacheData => ({ version: CACHE_VERSION, entries: [] }); const parseCache = (value: string | null): CacheData => { @@ -55,7 +60,7 @@ export class LocalNotificationCache { constructor(userId: string) { this.userId = userId; - this.storageKey = `sable.notificationCache.v1.${encodeURIComponent(userId)}`; + this.storageKey = storageKeyFor(userId); this.data = this.readStored(); window.addEventListener('storage', this.onStorageEvent); } @@ -297,7 +302,7 @@ export class LocalNotificationCache { export function clearLocalNotificationCache(userId: string): void { try { - globalThis.localStorage?.removeItem(`sable.notificationCache.v1.${encodeURIComponent(userId)}`); + globalThis.localStorage?.removeItem(storageKeyFor(userId)); } catch { // Storage can be disabled for this origin; logout must continue regardless. } diff --git a/src/client/slidingSyncSidebarCache.ts b/src/client/slidingSyncSidebarCache.ts index 8bdcff1d8..10c1a03d4 100644 --- a/src/client/slidingSyncSidebarCache.ts +++ b/src/client/slidingSyncSidebarCache.ts @@ -10,7 +10,7 @@ import { CustomAccountDataEvent } from '$types/matrix/accountData'; import { CustomStateEvent } from '$types/matrix/room'; const CACHE_VERSION = 1; -const CACHE_KEY_PREFIX = 'sable.slidingSyncSidebarCache.'; +export const SIDEBAR_CACHE_KEY_PREFIX = 'sable.slidingSyncSidebarCache.'; const CACHE_WRITE_DELAY_MS = 500; const MAX_CACHED_ROOMS = 2000; const HYDRATION_BATCH_SIZE = 50; @@ -169,7 +169,7 @@ const hydrateRoomBatch = async ( export class SlidingSyncSidebarCache { public static clear(userId: string): void { try { - globalThis.localStorage?.removeItem(`${CACHE_KEY_PREFIX}${encodeURIComponent(userId)}`); + globalThis.localStorage?.removeItem(`${SIDEBAR_CACHE_KEY_PREFIX}${encodeURIComponent(userId)}`); } catch { // Storage can be disabled for this origin. } @@ -184,7 +184,7 @@ export class SlidingSyncSidebarCache { private idleWriteHandle: number | undefined; public constructor(private readonly userId: string) { - this.storageKey = `${CACHE_KEY_PREFIX}${encodeURIComponent(userId)}`; + this.storageKey = `${SIDEBAR_CACHE_KEY_PREFIX}${encodeURIComponent(userId)}`; let stored: string | null = null; try { stored = globalThis.localStorage?.getItem(this.storageKey) ?? null;