From f9b452bde13fceb6d3b33806728b3336fc902369 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Thu, 5 Mar 2026 19:13:31 -0500 Subject: [PATCH 1/3] fix(notifications): SW push deep-links, visibility suppression, settings decoupling, nav fix - Rewrite notificationclick to deep-link via /to/:user_id/:room_id/:event_id so the correct account is activated on cold PWA launch (ToRoomEvent -> pendingNotificationAtom) - Suppress OS/SW push notification when the app window is already visible; track visibility via postMessage from the app on visibilitychange - Remove preferPushOnMobile dead code - Add useSystemNotifications setting (desktop-only, default true on desktop); split it out from useInAppNotifications so pill and OS notifications are independently controlled - Settings UI: desktop shows In-App + System Notifications; mobile shows In-App + Push Notifications; each hides the irrelevant third toggle - Fix InviteNotifications / MessageNotifications to gate OS notifications on useSystemNotifications + !mobileOrTablet(); pill remains gated on useInAppNotifications - Fix NotificationJumper: bypass useRoomNavigate (which routes through space path) -- navigate directly via getHomeRoomPath / getDirectRoomPath so tapping a pill banner on mobile opens the room timeline, not the space-nav panel - When the app is already open, use postMessage({ type: notificationClick }) from SW to the running window; new ServiceWorkerClickHandler component handles it with the same setActiveSessionId + setPending path as the pill flow; /to/ URL kept as cold-launch fallback only --- .../notifications/SystemNotification.tsx | 55 +++- src/app/hooks/useNotificationJumper.ts | 21 +- src/app/pages/client/ClientNonUIFeatures.tsx | 176 +++++++----- src/app/pages/client/ToRoomEvent.tsx | 41 ++- src/app/pages/paths.ts | 5 +- src/app/state/settings.ts | 11 +- src/sw.ts | 250 +++++++++++------- src/sw/pushNotification.ts | 1 + 8 files changed, 363 insertions(+), 197 deletions(-) diff --git a/src/app/features/settings/notifications/SystemNotification.tsx b/src/app/features/settings/notifications/SystemNotification.tsx index 04e31db79..38b3a7cca 100644 --- a/src/app/features/settings/notifications/SystemNotification.tsx +++ b/src/app/features/settings/notifications/SystemNotification.tsx @@ -14,6 +14,7 @@ import { useMatrixClient } from '$hooks/useMatrixClient'; import { useClientConfig } from '$hooks/useClientConfig'; import { SequenceCardStyle } from '$features/settings/styles.css'; import { pushSubscriptionAtom } from '$state/pushSubscription'; +import { mobileOrTablet } from '$utils/user-agent'; import { requestBrowserNotificationPermission, enablePushNotifications, @@ -165,6 +166,10 @@ function WebPushNotificationSetting() { export function SystemNotification() { const [showInAppNotifs, setShowInAppNotifs] = useSetting(settingsAtom, 'useInAppNotifications'); + const [showSystemNotifs, setShowSystemNotifs] = useSetting( + settingsAtom, + 'useSystemNotifications' + ); const [isNotificationSounds, setIsNotificationSounds] = useSetting( settingsAtom, 'isNotificationSounds' @@ -177,18 +182,14 @@ export function SystemNotification() { settingsAtom, 'showMessageContentInEncryptedNotifications' ); + const [clearNotificationsOnRead, setClearNotificationsOnRead] = useSetting( + settingsAtom, + 'clearNotificationsOnRead' + ); return ( System & Notifications - - - } /> + {mobileOrTablet() && ( + + + + )} + {!mobileOrTablet() && ( + + } + /> + + )} + + } + /> + { diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index f3bbfb26b..a85900a56 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -1,7 +1,7 @@ import { useAtomValue, useSetAtom } from 'jotai'; import { ReactNode, useCallback, useEffect, useRef } from 'react'; import { useNavigate } from 'react-router-dom'; -import { EventType, PushProcessor, RoomEvent, RoomEventHandlerMap } from '$types/matrix-sdk'; +import { PushProcessor, RoomEvent, RoomEventHandlerMap } from '$types/matrix-sdk'; import { roomToUnreadAtom } from '$state/room/roomToUnread'; import LogoSVG from '$public/res/svg/cinny.svg'; import { NotificationBanner } from '$components/notification-banner'; @@ -28,13 +28,13 @@ import { useSelectedRoom } from '$hooks/router/useSelectedRoom'; import { useInboxNotificationsSelected } from '$hooks/router/useInbox'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { registrationAtom } from '$state/serviceWorkerRegistration'; -import { activeSessionIdAtom, pendingNotificationAtom, inAppBannerAtom } from '$state/sessions'; +import { pendingNotificationAtom, inAppBannerAtom, activeSessionIdAtom } from '$state/sessions'; import { buildRoomMessageNotification, resolveNotificationPreviewText, } from '$utils/notificationStyle'; import { mobileOrTablet } from '$utils/user-agent'; -import { getInboxInvitesPath, getInboxNotificationsPath } from '../pathUtils'; +import { getInboxInvitesPath } from '../pathUtils'; import { BackgroundNotifications } from './BackgroundNotifications'; function SystemEmojiFeature() { @@ -70,9 +70,11 @@ function FaviconUpdater() { let notification = false; let highlight = false; let total = 0; + let highlightTotal = 0; roomToUnread.forEach((unread) => { if (unread.from === null) { total += unread.total; + highlightTotal += unread.highlight; } if (unread.total > 0) { notification = true; @@ -88,12 +90,17 @@ function FaviconUpdater() { setFavicon(LogoSVG); } try { - navigator.setAppBadge(total); + // Only badge with highlight (mention) counts — total unread is too noisy + // for an OS-level app badge. + if (highlightTotal > 0) { + navigator.setAppBadge(highlightTotal); + } else { + navigator.clearAppBadge(); + } if (usePushNotifications) { if (total === 0) { - // All rooms read — clear every notification and the badge. + // All rooms read — clear every notification. registration.getNotifications().then((notifs) => notifs.forEach((n) => n.close())); - navigator.clearAppBadge(); } else { // Dismiss notifications for individual rooms that are now fully read. registration.getNotifications().then((notifs) => { @@ -123,7 +130,7 @@ function InviteNotifications() { const mx = useMatrixClient(); const navigate = useNavigate(); - const [showNotifications] = useSetting(settingsAtom, 'useInAppNotifications'); + const [showSystemNotifications] = useSetting(settingsAtom, 'useSystemNotifications'); const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications'); const [notificationSound] = useSetting(settingsAtom, 'isNotificationSounds'); @@ -152,26 +159,26 @@ function InviteNotifications() { useEffect(() => { if (invites.length <= perviousInviteLen || mx.getSyncState() !== 'SYNCING') return; - // Page hidden: if push is enabled, SW handles the OS notification. If not, nothing to do. - if (document.visibilityState !== 'visible') return; + // SW push (via Sygnal) handles invite notifications when the app is backgrounded. + if (document.visibilityState !== 'visible' && usePushNotifications) return; - // Page is visible — show in-app experience. - // On mobile with push: iOS-style — play sound only, no OS notification (SW is silent when - // the app is visible on mobile, matching foreground behaviour of native chat apps). - // On desktop with push: SW skipped (saw a visible client), so we show the OS notification. - // Without push: always show OS notification when page is visible. - const isVisibleMobileWithPush = usePushNotifications && mobileOrTablet(); - if (!isVisibleMobileWithPush && showNotifications && notificationPermission('granted')) { - notify(invites.length - perviousInviteLen); + // OS notification for invites — desktop only. + if (!mobileOrTablet() && showSystemNotifications && notificationPermission('granted')) { + try { + notify(invites.length - perviousInviteLen); + } catch { + // window.Notification may be unavailable in sandboxed environments. + } } - if (notificationSound) { + // Audio API requires a visible document; skip when hidden. + if (document.visibilityState === 'visible' && notificationSound) { playSound(); } }, [ mx, invites, perviousInviteLen, - showNotifications, + showSystemNotifications, usePushNotifications, notificationSound, notify, @@ -189,9 +196,14 @@ function InviteNotifications() { function MessageNotifications() { const audioRef = useRef(null); const notifiedEventsRef = useRef>(new Set()); + // Record mount time so we can distinguish live events from historical backfill + // on sliding sync proxies that don't set num_live (which causes liveEvent=false + // for all events, including actually-new messages). + const clientStartTimeRef = useRef(Date.now()); const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const [showNotifications] = useSetting(settingsAtom, 'useInAppNotifications'); + const [showSystemNotifications] = useSetting(settingsAtom, 'useSystemNotifications'); const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications'); const [notificationSound] = useSetting(settingsAtom, 'isNotificationSounds'); const [showMessageContent] = useSetting(settingsAtom, 'showMessageContentInNotifications'); @@ -225,9 +237,23 @@ function MessageNotifications() { if (mx.getSyncState() !== 'SYNCING') return; if (document.hasFocus() && (selectedRoomId === room?.roomId || notificationSelected)) return; + // Older sliding sync proxies (e.g. matrix-sliding-sync) omit num_live, + // which causes every event to arrive with fromCache=true and therefore + // liveEvent=false — silently blocking all notifications. Fall back to an + // age check: treat the event as potentially live only when it was sent + // within 60 s of this component mounting (tight enough to avoid phantom + // notifications for pre-existing unread messages, generous enough for + // messages that arrived during a brief offline window). + // Additionally, skip the event if the user already has a read receipt + // covering it (message was read on another device before this session). + const isHistoricalEvent = + !data.liveEvent && + (mEvent.getTs() < clientStartTimeRef.current - 60 * 1000 || + (!!room && room.hasUserReadEvent(mx.getSafeUserId(), mEvent.getId()!))); + if ( !room || - !data.liveEvent || + isHistoricalEvent || room.isSpaceRoom() || !isNotificationEvent(mEvent) || getNotificationType(mx, room.roomId) === NotificationType.Mute @@ -309,10 +335,9 @@ function MessageNotifications() { }); } - // On desktop without push: also fire an OS notification as a secondary fallback - // so the user is alerted even if the browser window is minimised. - const isVisibleMobileWithPush = usePushNotifications && mobileOrTablet(); - if (!isVisibleMobileWithPush && showNotifications && notificationPermission('granted')) { + // On desktop: also fire an OS notification so the user is alerted even + // if the browser window is minimised (respects System Notifications toggle). + if (!mobileOrTablet() && showSystemNotifications && notificationPermission('granted')) { const isEncryptedRoom = !!getStateEvent(room, StateEvent.RoomEncryption); const avatarMxc = room.getAvatarFallbackMember()?.getMxcAvatarUrl() ?? room.getMxcAvatarUrl(); @@ -345,7 +370,10 @@ function MessageNotifications() { }; } - if (notificationSound && loudByRule) { + // In-app audio: play whenever notification sounds are enabled. + // Not gated on loudByRule — that only controls the OS-level silent flag. + // Audio API requires a visible, focused document; skip when hidden. + if (document.visibilityState === 'visible' && notificationSound) { playSound(); } }; @@ -358,6 +386,7 @@ function MessageNotifications() { notificationSound, notificationSelected, showNotifications, + showSystemNotifications, showMessageContent, showEncryptedMessageContent, usePushNotifications, @@ -394,55 +423,39 @@ type ClientNonUIFeaturesProps = { children: ReactNode; }; -export function HandleNotificationClick() { - const navigate = useNavigate(); - const setActiveSessionId = useSetAtom(activeSessionIdAtom); +function ServiceWorkerClickHandler() { const setPending = useSetAtom(pendingNotificationAtom); + const setActiveSessionId = useSetAtom(activeSessionIdAtom); + const navigate = useNavigate(); useEffect(() => { - const handleNotificationClickEvent = (event: any) => { - if (!event.data) return; - // Note: do NOT guard on event.source — iOS Safari sets it to null for - // SW-to-client postMessages (Webkit divergence from spec). The type check - // below is the correct way to filter unrelated messages. - const eventData = event.data; - if (!(eventData?.type === 'notificationToRoomEvent')) return; - const messageData = eventData?.message; - if (!messageData) { - navigate(getInboxNotificationsPath()); + if (!('serviceWorker' in navigator)) return undefined; + + const handleMessage = (ev: MessageEvent) => { + const { data } = ev; + if (!data || data.type !== 'notificationClick') return; + + const { userId, roomId, eventId, isInvite } = data as { + userId?: string; + roomId?: string; + eventId?: string; + isInvite?: boolean; + }; + + if (userId) setActiveSessionId(userId); + + if (isInvite) { + navigate(getInboxInvitesPath()); return; } - const targetSessionId = - typeof messageData?.user_id === 'string' ? messageData.user_id : undefined; - const eventType = messageData!.type as EventType; - switch (eventType) { - case EventType.RoomMessage: - case EventType.RoomMessageEncrypted: - // Always set the target session — jotai ignores no-ops if already active. - // This ensures we never accidentally navigate under the wrong account. - if (targetSessionId) setActiveSessionId(targetSessionId); - setPending({ - roomId: messageData!.room_id, - eventId: messageData!.event_id, - targetSessionId, - }); - return; - case EventType.RoomMember: - if (!(messageData?.content?.membership === 'invite')) return; - if (targetSessionId) setActiveSessionId(targetSessionId); - navigate(getInboxInvitesPath()); - break; - default: - break; - } + if (!roomId) return; + setPending({ roomId, eventId, targetSessionId: userId }); }; - navigator.serviceWorker.addEventListener('message', handleNotificationClickEvent); - return () => { - navigator.serviceWorker.removeEventListener('message', handleNotificationClickEvent); - }; - }, [navigate, setActiveSessionId, setPending]); + navigator.serviceWorker.addEventListener('message', handleMessage); + return () => navigator.serviceWorker.removeEventListener('message', handleMessage); + }, [setPending, setActiveSessionId, navigate]); return null; } @@ -455,25 +468,45 @@ function SyncNotificationSettingsWithServiceWorker() { settingsAtom, 'showMessageContentInEncryptedNotifications' ); + const [clearNotificationsOnRead] = useSetting(settingsAtom, 'clearNotificationsOnRead'); + + useEffect(() => { + if (!('serviceWorker' in navigator)) return undefined; + + const postVisibility = () => { + const visible = document.visibilityState === 'visible'; + const msg = { type: 'setAppVisible', visible }; + navigator.serviceWorker.controller?.postMessage(msg); + navigator.serviceWorker.ready.then((reg) => reg.active?.postMessage(msg)); + }; + + // Report initial visibility immediately, then track changes. + postVisibility(); + document.addEventListener('visibilitychange', postVisibility); + return () => document.removeEventListener('visibilitychange', postVisibility); + }, []); useEffect(() => { if (!('serviceWorker' in navigator)) return; - // preferPushOnMobile=false: SW skips push when page is visible on all devices. - // The in-app path handles the visible case (sound on mobile, OS notification on desktop). - const preferPushOnMobile = false; const payload = { type: 'setNotificationSettings' as const, notificationSoundEnabled: notificationSound, - preferPushOnMobile, showMessageContent, showEncryptedMessageContent, + clearNotificationsOnRead, }; navigator.serviceWorker.controller?.postMessage(payload); navigator.serviceWorker.ready.then((registration) => { registration.active?.postMessage(payload); }); - }, [notificationSound, usePushNotifications, showMessageContent, showEncryptedMessageContent]); + }, [ + notificationSound, + usePushNotifications, + showMessageContent, + showEncryptedMessageContent, + clearNotificationsOnRead, + ]); return null; } @@ -489,6 +522,7 @@ export function ClientNonUIFeatures({ children }: ClientNonUIFeaturesProps) { + {children} diff --git a/src/app/pages/client/ToRoomEvent.tsx b/src/app/pages/client/ToRoomEvent.tsx index 48321e66e..3073b44e9 100644 --- a/src/app/pages/client/ToRoomEvent.tsx +++ b/src/app/pages/client/ToRoomEvent.tsx @@ -1,35 +1,34 @@ import { useEffect } from 'react'; -import { useParams, useSearchParams } from 'react-router-dom'; +import { useParams } from 'react-router-dom'; import { useSetAtom } from 'jotai'; import { activeSessionIdAtom, pendingNotificationAtom } from '$state/sessions'; -// ToRoomEvent handles the /to/:room_id/:event_id route used by the SW when it -// opens a new window for a push notification (killed-app case) OR by client.navigate() -// on iOS where postMessage is unreliable after focus(). +// ToRoomEvent handles /to/:user_id/:room_id/:event_id? — the canonical deep-link +// URL used by the service worker's notificationclick handler. // -// It does NOT navigate itself. Instead it writes to pendingNotificationAtom so -// that NotificationJumper handles the actual navigation once the correct client -// is synced. This survives the ClientRoot account-switch reload that happens when -// setActiveSessionId() changes the active session: ToRoomEvent unmounts as soon -// as ClientRoot calls navigate(getHomePath()), but the atom value persists and -// NotificationJumper picks it up once the new client is ready. +// The :user_id segment lets the SW embed the target Matrix user ID directly in +// the URL (e.g. %40alice%3Aserver.tld) so the correct account is always +// activated before navigation, even on a cold launch where the app restarts +// from scratch after the PWA was killed by the OS. +// +// This component does NOT navigate itself — it writes to pendingNotificationAtom +// so NotificationJumper can navigate once the Matrix client has finished its +// initial sync. The atom survives the ClientRoot reload that happens when +// setActiveSessionId() triggers an account switch. export function ToRoomEvent() { - const { room_id: roomId, event_id: eventId } = useParams(); - const [searchParams] = useSearchParams(); - const targetUserId = searchParams.get('uid') ?? undefined; + const { user_id: userId, room_id: roomId, event_id: eventId } = useParams(); const setActiveSessionId = useSetAtom(activeSessionIdAtom); const setPending = useSetAtom(pendingNotificationAtom); useEffect(() => { if (!roomId) return; - const rid = roomId; // narrowed to string - if (targetUserId) setActiveSessionId(targetUserId); - setPending({ roomId: rid, eventId, targetSessionId: targetUserId }); - // Push a clean entry onto history so the back button doesn't return to /to/… - if (window.history.length <= 2) { - window.history.pushState({}, '', '/'); - } - }, [roomId, eventId, targetUserId, setActiveSessionId, setPending]); + // Switch to the target account first so the notification jumper navigates + // under the correct session. + if (userId) setActiveSessionId(userId); + setPending({ roomId, eventId, targetSessionId: userId }); + // Replace /to/… in history so the back button doesn't return to this route. + window.history.replaceState({}, '', '/'); + }, [userId, roomId, eventId, setActiveSessionId, setPending]); return null; } diff --git a/src/app/pages/paths.ts b/src/app/pages/paths.ts index 06878fd37..82f8c6dd2 100644 --- a/src/app/pages/paths.ts +++ b/src/app/pages/paths.ts @@ -86,7 +86,10 @@ export const INBOX_NOTIFICATIONS_PATH = `/inbox/${NOTIFICATIONS_PATH_SEGMENT}`; export const INBOX_INVITES_PATH = `/inbox/${INVITES_PATH_SEGMENT}`; export const TO_PATH = '/to'; -export const TO_ROOM_EVENT_PATH = `${TO_PATH}/:room_id/:event_id?`; +// Deep-link route used by push notification click-back URLs. +// Format: /to/:user_id/:room_id/:event_id? +// e.g. /to/%40alice%3Aserver/%21room%3Aserver/%24event%3Aserver +export const TO_ROOM_EVENT_PATH = `${TO_PATH}/:user_id/:room_id/:event_id?`; export const SPACE_SETTINGS_PATH = '/space-settings/'; diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index fab455280..47b42da58 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -1,4 +1,5 @@ import { atom } from 'jotai'; +import { mobileOrTablet } from '$utils/user-agent'; const STORAGE_KEY = 'settings'; export type DateFormat = 'D MMM YYYY' | 'DD/MM/YYYY' | 'MM/DD/YYYY' | 'YYYY/MM/DD' | ''; @@ -45,9 +46,11 @@ export interface Settings { usePushNotifications: boolean; useInAppNotifications: boolean; + useSystemNotifications: boolean; isNotificationSounds: boolean; showMessageContentInNotifications: boolean; showMessageContentInEncryptedNotifications: boolean; + clearNotificationsOnRead: boolean; hour24Clock: boolean; dateFormatString: string; @@ -102,11 +105,17 @@ const defaultSettings: Settings = { showHiddenEvents: false, legacyUsernameColor: false, - usePushNotifications: false, + // Push notifications (SW/Sygnal): default on for mobile, opt-in on desktop. + // In-app pill banner: always on — it's the primary foreground alert on mobile + // and a useful secondary alert on desktop. + // System (OS) notifications: desktop-only; hidden and disabled on mobile. + usePushNotifications: mobileOrTablet(), useInAppNotifications: true, + useSystemNotifications: !mobileOrTablet(), isNotificationSounds: true, showMessageContentInNotifications: false, showMessageContentInEncryptedNotifications: false, + clearNotificationsOnRead: false, hour24Clock: false, dateFormatString: 'D MMM YYYY', diff --git a/src/sw.ts b/src/sw.ts index 87fbc3488..7185fbd30 100644 --- a/src/sw.ts +++ b/src/sw.ts @@ -1,16 +1,20 @@ /// // eslint-disable-next-line import-x/no-extraneous-dependencies import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching'; -import { EventType } from 'matrix-js-sdk/lib/@types/event'; + import { createPushNotifications } from './sw/pushNotification'; export type {}; declare const self: ServiceWorkerGlobalScope; let notificationSoundEnabled = true; -let preferPushOnMobile = false; +// Tracks whether a page client has reported itself as visible. +// The clients.matchAll() visibilityState is unreliable on iOS Safari PWA, +// so we use this explicit flag as a fallback. +let appIsVisible = false; let showMessageContent = false; let showEncryptedMessageContent = false; +let clearNotificationsOnRead = false; const { handlePushNotificationPushData } = createPushNotifications(self, () => ({ notificationSoundEnabled, showMessageContent, @@ -29,9 +33,9 @@ async function persistSettings() { new Response( JSON.stringify({ notificationSoundEnabled, - preferPushOnMobile, showMessageContent, showEncryptedMessageContent, + clearNotificationsOnRead, }), { headers: { 'Content-Type': 'application/json' } } ) @@ -49,10 +53,11 @@ async function loadPersistedSettings() { const s = await response.json(); if (typeof s.notificationSoundEnabled === 'boolean') notificationSoundEnabled = s.notificationSoundEnabled; - if (typeof s.preferPushOnMobile === 'boolean') preferPushOnMobile = s.preferPushOnMobile; if (typeof s.showMessageContent === 'boolean') showMessageContent = s.showMessageContent; if (typeof s.showEncryptedMessageContent === 'boolean') showEncryptedMessageContent = s.showEncryptedMessageContent; + if (typeof s.clearNotificationsOnRead === 'boolean') + clearNotificationsOnRead = s.clearNotificationsOnRead; } catch { // Ignore — stale or missing cache is fine; we fall back to defaults. } @@ -159,6 +164,11 @@ self.addEventListener('message', (event: ExtendableMessageEvent) => { setSession(client.id, accessToken, baseUrl); event.waitUntil(cleanupDeadClients()); } + if (type === 'setAppVisible') { + if (typeof (data as { visible?: unknown }).visible === 'boolean') { + appIsVisible = (data as { visible: boolean }).visible; + } + } if (type === 'setNotificationSettings') { if ( typeof (data as { notificationSoundEnabled?: unknown }).notificationSoundEnabled === 'boolean' @@ -166,9 +176,6 @@ self.addEventListener('message', (event: ExtendableMessageEvent) => { notificationSoundEnabled = (data as { notificationSoundEnabled: boolean }) .notificationSoundEnabled; } - if (typeof (data as { preferPushOnMobile?: unknown }).preferPushOnMobile === 'boolean') { - preferPushOnMobile = (data as { preferPushOnMobile: boolean }).preferPushOnMobile; - } if (typeof (data as { showMessageContent?: unknown }).showMessageContent === 'boolean') { showMessageContent = (data as { showMessageContent: boolean }).showMessageContent; } @@ -179,12 +186,27 @@ self.addEventListener('message', (event: ExtendableMessageEvent) => { showEncryptedMessageContent = (data as { showEncryptedMessageContent: boolean }) .showEncryptedMessageContent; } + if ( + typeof (data as { clearNotificationsOnRead?: unknown }).clearNotificationsOnRead === 'boolean' + ) { + clearNotificationsOnRead = (data as { clearNotificationsOnRead: boolean }) + .clearNotificationsOnRead; + } // Persist so settings survive SW restart (iOS kills the SW aggressively). event.waitUntil(persistSettings()); } }); -const MEDIA_PATHS = ['/_matrix/client/v1/media/download', '/_matrix/client/v1/media/thumbnail']; +const MEDIA_PATHS = [ + '/_matrix/client/v1/media/download', + '/_matrix/client/v1/media/thumbnail', + // Legacy unauthenticated endpoints — servers that require auth return 404/403 + // for these when no token is present, so intercept and add auth here too. + '/_matrix/media/v3/download', + '/_matrix/media/v3/thumbnail', + '/_matrix/media/r0/download', + '/_matrix/media/r0/thumbnail', +]; function mediaPath(url: string): boolean { try { @@ -233,10 +255,17 @@ self.addEventListener('fetch', (event: FetchEvent) => { const { clientId } = event; if (!clientId) return; + // For browser sub-resource loads (images, video, audio, etc.), 'follow' is + // the correct mode: the auth header is sent to the Matrix server which owns + // the first hop; any CDN redirect it issues is followed natively by the + // Fetch machinery. 'manual' would return an opaque-redirect Response that + // the browser cannot render as an /