From b45290d16f516faf65b05596a7f613d9f3c4e38e Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 18:55:06 -0500
Subject: [PATCH 01/83] Add a public key for VAPID, push ID, and push endpoint
(I'm willing to publicly host it unless it becomes irrational in cost which
should never happen)
---
config.json | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/config.json b/config.json
index de6015a10..dc03d4879 100644
--- a/config.json
+++ b/config.json
@@ -10,6 +10,12 @@
],
"allowCustomHomeservers": true,
+ "pushNotificationDetails": {
+ "pushNotifyUrl": "https://cinny.cc/_matrix/push/v1/notify",
+ "vapidPublicKey": "BHLwykXs79AbKNiblEtZZRAgnt7o5_ieImhVJD8QZ01MVwAHnXwZzNgQEJJEU3E5CVsihoKtb7yaNe5x3vmkWkI",
+ "webPushAppID": "cc.cinny.web"
+ },
+
"featuredCommunities": {
"openAsDefault": false,
"spaces": [
From 5f52e932aede15afe51812126904b7f9b8a0cdc2 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 18:57:59 -0500
Subject: [PATCH 02/83] add workbox precaching (for SW caching)
---
package.json | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/package.json b/package.json
index b1b14e55d..f278255a5 100644
--- a/package.json
+++ b/package.json
@@ -113,6 +113,7 @@
"vite": "5.4.15",
"vite-plugin-pwa": "0.20.5",
"vite-plugin-static-copy": "1.0.4",
- "vite-plugin-top-level-await": "1.4.4"
+ "vite-plugin-top-level-await": "1.4.4",
+ "workbox-precaching": "7.3.0"
}
}
From 4cc1179a4f6b253fd8e32fa9b9bf66b3b71197c3 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 19:00:39 -0500
Subject: [PATCH 03/83] Add claim and install events
---
src/sw.ts | 10 +++++++++-
1 file changed, 9 insertions(+), 1 deletion(-)
diff --git a/src/sw.ts b/src/sw.ts
index 2179dfcb8..d2b03b3de 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -28,7 +28,15 @@ function fetchConfig(token?: string): RequestInit | undefined {
}
self.addEventListener('activate', (event: ExtendableEvent) => {
- event.waitUntil(clients.claim());
+ event.waitUntil(
+ (async () => {
+ await self.clients.claim();
+ })()
+ );
+});
+
+self.addEventListener('install', (event: ExtendableEvent) => {
+ event.waitUntil(self.skipWaiting());
});
self.addEventListener('fetch', (event: FetchEvent) => {
From 14085c7ccf74f819b68755391b0a160651dd4d3d Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 19:02:03 -0500
Subject: [PATCH 04/83] Convert to a more generic implementation for
communicating with the client
---
src/sw.ts | 34 ++++++++++++++++++++++++----------
1 file changed, 24 insertions(+), 10 deletions(-)
diff --git a/src/sw.ts b/src/sw.ts
index d2b03b3de..419be5345 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -3,19 +3,33 @@
export type {};
declare const self: ServiceWorkerGlobalScope;
-async function askForAccessToken(client: Client): Promise {
- return new Promise((resolve) => {
- const responseKey = Math.random().toString(36);
- const listener = (event: ExtendableMessageEvent) => {
- if (event.data.responseKey !== responseKey) return;
- resolve(event.data.token);
- self.removeEventListener('message', listener);
- };
- self.addEventListener('message', listener);
- client.postMessage({ responseKey, type: 'token' });
+const DEFAULT_NOTIFICATION_ICON = '/icons/icon-192x192.png'; // Replace with your actual default icon path
+const DEFAULT_NOTIFICATION_BADGE = '/icons/badge-72x72.png'; // Replace with your actual default badge icon path (for notification UI)
+
+const pendingReplies = new Map();
+let messageIdCounter = 0;
+function sendAndWaitForReply(client: WindowClient, type: string, payload: object) {
+ messageIdCounter += 1;
+ const id = messageIdCounter;
+ const promise = new Promise((resolve) => {
+ pendingReplies.set(id, resolve);
});
+ client.postMessage({ type, id, payload });
+ return promise;
}
+self.addEventListener('message', (event) => {
+ const { replyTo } = event.data;
+ if (replyTo) {
+ const resolve = pendingReplies.get(replyTo);
+ if (resolve) {
+ pendingReplies.delete(replyTo);
+ resolve(event.data.payload);
+ }
+ }
+});
+
+
function fetchConfig(token?: string): RequestInit | undefined {
if (!token) return undefined;
From 5029ea0a8ae8f854b8b93b15cb36ea0d594de5e6 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:04:22 -0500
Subject: [PATCH 05/83] add precaching from workbox import
---
src/sw.ts | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/sw.ts b/src/sw.ts
index 419be5345..ffc5c0e14 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -1,4 +1,5 @@
///
+import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
export type {};
declare const self: ServiceWorkerGlobalScope;
From 4968e23dffee810e5e99a599f340415f0da150ee Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:04:38 -0500
Subject: [PATCH 06/83] actually set the path (should fix android blank icon
issue)
---
src/sw.ts | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/sw.ts b/src/sw.ts
index ffc5c0e14..4a664c1f8 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -4,8 +4,8 @@ import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
export type {};
declare const self: ServiceWorkerGlobalScope;
-const DEFAULT_NOTIFICATION_ICON = '/icons/icon-192x192.png'; // Replace with your actual default icon path
-const DEFAULT_NOTIFICATION_BADGE = '/icons/badge-72x72.png'; // Replace with your actual default badge icon path (for notification UI)
+const DEFAULT_NOTIFICATION_ICON = '/public/res/apple/apple-touch-icon-180x180.png';
+const DEFAULT_NOTIFICATION_BADGE = '/public/res/apple-touch-icon-72x72.png';
const pendingReplies = new Map();
let messageIdCounter = 0;
From 3b62beabf1dee0510d6c66d96ffe3d50c77c6e2a Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:04:55 -0500
Subject: [PATCH 07/83] add param type
---
src/sw.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/sw.ts b/src/sw.ts
index 4a664c1f8..62db9e950 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -19,7 +19,7 @@ function sendAndWaitForReply(client: WindowClient, type: string, payload: object
return promise;
}
-self.addEventListener('message', (event) => {
+self.addEventListener('message', (event: ExtendableMessageEvent) => {
const { replyTo } = event.data;
if (replyTo) {
const resolve = pendingReplies.get(replyTo);
From 1d4864592fc60f57e5124ccde1b167950ae33bf4 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:05:28 -0500
Subject: [PATCH 08/83] Clean up fetch code
---
src/sw.ts | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/src/sw.ts b/src/sw.ts
index 62db9e950..16ee5de5f 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -65,11 +65,11 @@ self.addEventListener('fetch', (event: FetchEvent) => {
}
event.respondWith(
(async (): Promise => {
+ console.log('Unironic race condition mitigation it seems.');
const client = await self.clients.get(event.clientId);
- let token: string | undefined;
- if (client) token = await askForAccessToken(client);
-
- return fetch(url, fetchConfig(token));
+ const token: string = await sendAndWaitForReply(client, 'token', {});
+ const response = await fetch(url, fetchConfig(token));
+ return response;
})()
);
});
From c77ba1b5342535c22df2789939c0239596769a91 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:07:24 -0500
Subject: [PATCH 09/83] Add push notif handling (clicks and push events)
---
src/sw.ts | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 77 insertions(+)
diff --git a/src/sw.ts b/src/sw.ts
index 16ee5de5f..ac86f6222 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -73,3 +73,80 @@ self.addEventListener('fetch', (event: FetchEvent) => {
})()
);
});
+
+const onPushNotification = async (event: PushEvent) => {
+ let title = 'New Notification';
+ const options: NotificationOptions = {
+ body: 'You have a new message!',
+ icon: DEFAULT_NOTIFICATION_ICON,
+ badge: DEFAULT_NOTIFICATION_BADGE,
+ data: {
+ url: self.registration.scope,
+ timestamp: Date.now(),
+ },
+ // tag: 'cinny-notification-tag', // Optional: Replaces existing notification with same tag
+ // renotify: true, // Optional: If using tag, renotify will alert user even if tag matches
+ // silent: false, // Optional: Set to true for no sound/vibration. User can also set this.
+ };
+
+ if (event.data) {
+ try {
+ const pushData = event.data.json();
+ title = pushData.title || title;
+ options.body = options.body ?? pushData.data.toString();
+ options.icon = pushData.icon || options.icon;
+ options.badge = pushData.badge || options.badge;
+
+ if (pushData.image) options.image = pushData.image;
+ if (pushData.vibrate) options.vibrate = pushData.vibrate;
+ if (pushData.actions) options.actions = pushData.actions;
+ options.tag = 'Cinny';
+ if (typeof pushData.renotify === 'boolean') options.renotify = pushData.renotify;
+ if (typeof pushData.silent === 'boolean') options.silent = pushData.silent;
+
+ if (pushData.data) {
+ options.data = { ...options.data, ...pushData.data };
+ }
+ if (typeof pushData.unread === 'number') {
+ await self.navigator.setAppBadge(pushData.unread);
+ } else {
+ await navigator.clearAppBadge();
+ }
+ } catch (e) {
+ const pushText = event.data.text();
+ options.body = pushText || options.body;
+ }
+ }
+
+ return self.registration.showNotification(title, options);
+};
+
+self.addEventListener('push', (event: PushEvent) => event.waitUntil(onPushNotification(event)));
+
+self.addEventListener('notificationclick', (event: NotificationEvent) => {
+ event.notification.close();
+
+ /**
+ * We should likely add a postMessage back to navigate to the room the event is from
+ */
+ const targetUrl = event.notification.data?.url || self.registration.scope;
+
+ event.waitUntil(
+ self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
+ for (const client of clientList) {
+ if (client.url === targetUrl && 'focus' in client) {
+ return (client as WindowClient).focus();
+ }
+ }
+ if (self.clients.openWindow) {
+ return self.clients.openWindow(targetUrl);
+ }
+ return Promise.resolve();
+ })
+ );
+});
+
+if (self.__WB_MANIFEST) {
+ precacheAndRoute(self.__WB_MANIFEST);
+}
+cleanupOutdatedCaches();
From ca026bf9472332433df084f56a133d1b89c67b9d Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:08:44 -0500
Subject: [PATCH 10/83] Add SW update prompt (useful for rolling out new
changes and informing the user of them)
---
src/index.tsx | 38 +++++++++++++++++++++++++++++++++++++-
1 file changed, 37 insertions(+), 1 deletion(-)
diff --git a/src/index.tsx b/src/index.tsx
index 402a4c1b7..da60808a4 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -25,7 +25,43 @@ if ('serviceWorker' in navigator) {
? `${trimTrailingSlash(import.meta.env.BASE_URL)}/sw.js`
: `/dev-sw.js?dev-sw`;
- navigator.serviceWorker.register(swUrl);
+ const swRegisterOptions: RegistrationOptions = {};
+ if (!isProduction) {
+ swRegisterOptions.type = 'module';
+ }
+
+ const showUpdateAvailablePrompt = (registration: ServiceWorkerRegistration) => {
+ const DONT_SHOW_PROMPT_KEY = 'cinny_dont_show_sw_update_prompt';
+ const userPreference = localStorage.getItem(DONT_SHOW_PROMPT_KEY);
+
+ if (userPreference === 'true') {
+ return;
+ }
+
+ if (window.confirm('A new version of the app is available. Refresh to update?')) {
+ if (registration.waiting) {
+ registration.waiting.postMessage({ type: 'SKIP_WAITING_AND_CLAIM' });
+ } else {
+ window.location.reload();
+ }
+ }
+ };
+
+ navigator.serviceWorker.register(swUrl, swRegisterOptions).then((registration) => {
+ registration.onupdatefound = () => {
+ const installingWorker = registration.installing;
+ if (installingWorker) {
+ installingWorker.onstatechange = () => {
+ if (installingWorker.state === 'installed') {
+ if (navigator.serviceWorker.controller) {
+ showUpdateAvailablePrompt(registration);
+ }
+ }
+ };
+ }
+ };
+ });
+
navigator.serviceWorker.addEventListener('message', (event) => {
if (event.data?.type === 'token' && event.data?.responseKey) {
// Get the token for SW.
From f6acd72ab519d78fe5399b17f6158d1d224a101c Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:10:05 -0500
Subject: [PATCH 11/83] Add isProduction to determine the behavior to use for
the SW
---
src/index.tsx | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
diff --git a/src/index.tsx b/src/index.tsx
index da60808a4..a65466e2c 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -18,10 +18,9 @@ import './app/i18n';
document.body.classList.add(configClass, varsClass);
-// Register Service Worker
if ('serviceWorker' in navigator) {
- const swUrl =
- import.meta.env.MODE === 'production'
+ const isProduction = import.meta.env.MODE === 'production';
+ const swUrl = isProduction
? `${trimTrailingSlash(import.meta.env.BASE_URL)}/sw.js`
: `/dev-sw.js?dev-sw`;
From 1db4685189c8efc18a4578a22544a01461744cee Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:13:10 -0500
Subject: [PATCH 12/83] Embed a very simple message handler between the SW and
client for now (for token auth atm)
---
src/index.tsx | 20 +++++++++++++++-----
1 file changed, 15 insertions(+), 5 deletions(-)
diff --git a/src/index.tsx b/src/index.tsx
index a65466e2c..fd3ec6be8 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -62,13 +62,23 @@ if ('serviceWorker' in navigator) {
});
navigator.serviceWorker.addEventListener('message', (event) => {
- if (event.data?.type === 'token' && event.data?.responseKey) {
- // Get the token for SW.
+ if (!event.data || !event.source) {
+ return;
+ }
+
+ if (event.data.type === 'token' && event.data.id) {
const token = localStorage.getItem('cinny_access_token') ?? undefined;
- event.source!.postMessage({
- responseKey: event.data.responseKey,
- token,
+ event.source.postMessage({
+ replyTo: event.data.id,
+ payload: token,
});
+ } else if (event.data.type === 'openRoom' && event.data.id) {
+ /* Example:
+ event.source.postMessage({
+ replyTo: event.data.id,
+ payload: success?,
+ });
+ */
}
});
}
From 36227ef2579ad63aaa8f1adf045a022e2638cc9a Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:13:38 -0500
Subject: [PATCH 13/83] Move MapSet position
---
src/index.tsx | 2 ++
1 file changed, 2 insertions(+)
diff --git a/src/index.tsx b/src/index.tsx
index fd3ec6be8..ef9baa7fc 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -16,6 +16,8 @@ import App from './app/pages/App';
// import i18n (needs to be bundled ;))
import './app/i18n';
+enableMapSet();
+
document.body.classList.add(configClass, varsClass);
if ('serviceWorker' in navigator) {
From 4af54629f792d7a2b089409bb492e78bd30b597a Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:13:59 -0500
Subject: [PATCH 14/83] clean up imports
---
src/index.tsx | 6 ------
1 file changed, 6 deletions(-)
diff --git a/src/index.tsx b/src/index.tsx
index ef9baa7fc..c79fa6ad2 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -5,15 +5,9 @@ import { enableMapSet } from 'immer';
import '@fontsource/inter/variable.css';
import 'folds/dist/style.css';
import { configClass, varsClass } from 'folds';
-
-enableMapSet();
-
import './index.scss';
-
import { trimTrailingSlash } from './app/utils/common';
import App from './app/pages/App';
-
-// import i18n (needs to be bundled ;))
import './app/i18n';
enableMapSet();
From 8a3eee367d7b3aebff653d85b549a136beefecb6 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:14:15 -0500
Subject: [PATCH 15/83] remove disable import
---
src/index.tsx | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
diff --git a/src/index.tsx b/src/index.tsx
index c79fa6ad2..f5118555d 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -1,4 +1,3 @@
-/* eslint-disable import/first */
import React from 'react';
import { createRoot } from 'react-dom/client';
import { enableMapSet } from 'immer';
@@ -17,8 +16,8 @@ document.body.classList.add(configClass, varsClass);
if ('serviceWorker' in navigator) {
const isProduction = import.meta.env.MODE === 'production';
const swUrl = isProduction
- ? `${trimTrailingSlash(import.meta.env.BASE_URL)}/sw.js`
- : `/dev-sw.js?dev-sw`;
+ ? `${trimTrailingSlash(import.meta.env.BASE_URL)}/sw.js`
+ : `/dev-sw.js?dev-sw`;
const swRegisterOptions: RegistrationOptions = {};
if (!isProduction) {
From a8839633146846b1bc77b22e2c3679cc93ff1189 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:15:45 -0500
Subject: [PATCH 16/83] Adds the client state listener for toggling whether to
use push notifs or app notifs
---
src/app/pages/client/ClientRoot.tsx | 28 ++++++++++++++++++++++------
1 file changed, 22 insertions(+), 6 deletions(-)
diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx
index 846d8ff3f..8eac63bd2 100644
--- a/src/app/pages/client/ClientRoot.tsx
+++ b/src/app/pages/client/ClientRoot.tsx
@@ -37,6 +37,7 @@ import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
import { useSyncState } from '../../hooks/useSyncState';
import { stopPropagation } from '../../utils/keyboard';
import { SyncStatus } from './SyncStatus';
+import { togglePusher } from '../../features/settings/notifications/PushNotifications';
function ClientRootLoading() {
return (
@@ -124,6 +125,18 @@ function ClientRootOptions({ mx }: { mx?: MatrixClient }) {
);
}
+const pushNotificationListener = (mx: MatrixClient) => {
+ navigator.serviceWorker.ready.then((registration) => {
+ registration.pushManager.getSubscription().then((subscription) => {
+ document.addEventListener('visibilitychange', () => {
+ console.log('Check check baby');
+ togglePusher(mx, subscription, document.visibilityState === 'visible');
+ });
+ togglePusher(mx, subscription, true);
+ });
+ });
+};
+
const useLogoutListener = (mx?: MatrixClient) => {
useEffect(() => {
const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = async () => {
@@ -171,13 +184,16 @@ export function ClientRoot({ children }: ClientRootProps) {
useSyncState(
mx,
- useCallback((state) => {
- if (state === 'PREPARED') {
- setLoading(false);
- }
- }, [])
+ useCallback(
+ (state) => {
+ if (state === 'PREPARED') {
+ setLoading(false);
+ pushNotificationListener(mx);
+ }
+ },
+ [mx]
+ )
);
-
return (
{mx && }
From ac5925f293f8a8e44238afc50baff554995bc966 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:16:44 -0500
Subject: [PATCH 17/83] Add a check for our custom tweak in the in-app notif
handling to determine which should be used
---
src/app/pages/client/ClientNonUIFeatures.tsx | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx
index ce952bfc6..0e2d5d678 100644
--- a/src/app/pages/client/ClientNonUIFeatures.tsx
+++ b/src/app/pages/client/ClientNonUIFeatures.tsx
@@ -187,12 +187,15 @@ function MessageNotifications() {
) => {
if (mx.getSyncState() !== 'SYNCING') return;
if (document.hasFocus() && (selectedRoomId === room?.roomId || notificationSelected)) return;
+ let pushActions = mx.getPushActionsForEvent(mEvent);
+ const hasInAppTweak = pushActions?.tweaks?.sound === 'cinny_show_banner';
+
if (
!room ||
!data.liveEvent ||
room.isSpaceRoom() ||
!isNotificationEvent(mEvent) ||
- getNotificationType(mx, room.roomId) === NotificationType.Mute
+ (getNotificationType(mx, room.roomId) === NotificationType.Mute && !hasInAppTweak)
) {
return;
}
From e2fbf9e738f0cde5e1627bcfb346205d6fb3a3b7 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:44:55 -0500
Subject: [PATCH 18/83] Add WebPush separate toggle
---
.../notifications/SystemNotification.tsx | 104 ++++++++++++++++++
1 file changed, 104 insertions(+)
diff --git a/src/app/features/settings/notifications/SystemNotification.tsx b/src/app/features/settings/notifications/SystemNotification.tsx
index e0df06df9..a5470dd7b 100644
--- a/src/app/features/settings/notifications/SystemNotification.tsx
+++ b/src/app/features/settings/notifications/SystemNotification.tsx
@@ -84,6 +84,110 @@ function EmailNotification() {
);
}
+function WebPushNotificationSetting() {
+ const mx = useMatrixClient();
+ const clientConfig = useClientConfig();
+ const [userWantsWebPush, setUserWantsWebPush] = useSetting(settingsAtom, 'enableWebPush');
+
+ const browserPermission = usePermissionState('notifications', getNotificationState());
+ const [isPushSubscribed, setIsPushSubscribed] = useState(false);
+ const [isLoading, setIsLoading] = useState(true); // Start loading to check status
+
+ const checkSubscriptionStatus = useCallback(async () => {
+ if (
+ browserPermission === 'granted' &&
+ 'serviceWorker' in navigator &&
+ 'PushManager' in window
+ ) {
+ setIsLoading(true);
+ try {
+ const registration = await navigator.serviceWorker.ready;
+ const subscription = await registration.pushManager.getSubscription();
+ setIsPushSubscribed(!!subscription);
+ } catch (err) {
+ setIsPushSubscribed(false);
+ } finally {
+ setIsLoading(false);
+ }
+ } else {
+ setIsPushSubscribed(false);
+ setIsLoading(false);
+ }
+ }, [browserPermission]);
+
+ useEffect(() => {
+ checkSubscriptionStatus();
+ }, [checkSubscriptionStatus]);
+
+ const handleRequestPermissionAndEnable = async () => {
+ setIsLoading(true);
+ try {
+ const permissionResult = await requestBrowserNotificationPermission();
+ if (permissionResult === 'granted') {
+ setUserWantsWebPush(true);
+ await enablePushNotifications(mx, clientConfig);
+ } else {
+ setUserWantsWebPush(false);
+ }
+ } catch (error: any) {
+ setUserWantsWebPush(false);
+ } finally {
+ await checkSubscriptionStatus();
+ setIsLoading(false);
+ }
+ };
+
+ const handlePushSwitchChange = async (wantsPush: boolean) => {
+ setIsLoading(true);
+ setUserWantsWebPush(wantsPush);
+
+ try {
+ if (wantsPush) {
+ await enablePushNotifications(mx, clientConfig);
+ } else {
+ await disablePushNotifications(mx, clientConfig);
+ }
+ } catch (error: any) {
+ setUserWantsWebPush(!wantsPush);
+ } finally {
+ await checkSubscriptionStatus();
+ setIsLoading(false);
+ }
+ };
+
+ let descriptionText = 'Receive notifications when the app is closed or in the background.';
+ if (browserPermission === 'granted' && isPushSubscribed) {
+ descriptionText =
+ 'You are subscribed to receive notifications when the app is in the background.';
+ }
+
+ return (
+
+ Notification permission is blocked by your browser. Please allow it from site settings.
+
+ ) : (
+ {descriptionText}
+ )
+ }
+ after={
+ isLoading ? (
+
+ ) : browserPermission === 'prompt' ? (
+
+ ) : browserPermission === 'granted' ? (
+
+ ) : null
+ }
+ />
+ );
+}
+
export function SystemNotification() {
const notifPermission = usePermissionState('notifications', getNotificationState());
const [showNotifications, setShowNotifications] = useSetting(settingsAtom, 'showNotifications');
From a271a5647e95e400ca7c05c7547140646b535faa Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:45:43 -0500
Subject: [PATCH 19/83] Add render changes
---
.../notifications/SystemNotification.tsx | 47 ++++++-------------
1 file changed, 14 insertions(+), 33 deletions(-)
diff --git a/src/app/features/settings/notifications/SystemNotification.tsx b/src/app/features/settings/notifications/SystemNotification.tsx
index a5470dd7b..deb775a0b 100644
--- a/src/app/features/settings/notifications/SystemNotification.tsx
+++ b/src/app/features/settings/notifications/SystemNotification.tsx
@@ -189,20 +189,23 @@ function WebPushNotificationSetting() {
}
export function SystemNotification() {
- const notifPermission = usePermissionState('notifications', getNotificationState());
- const [showNotifications, setShowNotifications] = useSetting(settingsAtom, 'showNotifications');
+ const [showInAppNotifs, setShowInAppNotifs] = useSetting(settingsAtom, 'showNotifications');
const [isNotificationSounds, setIsNotificationSounds] = useSetting(
settingsAtom,
'isNotificationSounds'
);
- const requestNotificationPermission = () => {
- window.Notification.requestPermission();
- };
-
return (
- System
+ System & Notifications
+
+
+
- {'Notification' in window
- ? 'Notification permission is blocked. Please allow notification permission from browser address bar.'
- : 'Notifications are not supported by the system.'}
-
- ) : (
- Show desktop notifications when message arrive.
- )
- }
- after={
- notifPermission === 'prompt' ? (
-
- ) : (
-
- )
- }
+ title="In-App Notifications"
+ description="Show a notification when a message arrives while the app is open (but not focused on the room)."
+ after={}
/>
}
/>
From b801f076a773924ac9c9bbb45f0c42aadc4fb277 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:45:57 -0500
Subject: [PATCH 20/83] update imports
---
.../settings/notifications/SystemNotification.tsx | 9 +++++++--
1 file changed, 7 insertions(+), 2 deletions(-)
diff --git a/src/app/features/settings/notifications/SystemNotification.tsx b/src/app/features/settings/notifications/SystemNotification.tsx
index deb775a0b..6e292dd80 100644
--- a/src/app/features/settings/notifications/SystemNotification.tsx
+++ b/src/app/features/settings/notifications/SystemNotification.tsx
@@ -1,6 +1,5 @@
-import React, { useCallback } from 'react';
+import React, { useCallback, useEffect, useState } from 'react';
import { Box, Text, Switch, Button, color, Spinner } from 'folds';
-import { IPusherRequest } from 'matrix-js-sdk';
import { SequenceCard } from '../../../components/sequence-card';
import { SequenceCardStyle } from '../styles.css';
import { SettingTile } from '../../../components/setting-tile';
@@ -10,6 +9,12 @@ import { getNotificationState, usePermissionState } from '../../../hooks/usePerm
import { useEmailNotifications } from '../../../hooks/useEmailNotifications';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
+import {
+ requestBrowserNotificationPermission,
+ enablePushNotifications,
+ disablePushNotifications,
+} from './PushNotifications';
+import { useClientConfig } from '../../../hooks/useClientConfig';
function EmailNotification() {
const mx = useMatrixClient();
From e38eeb30bda871219fd33e6a1b98ff5754e4284c Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:46:19 -0500
Subject: [PATCH 21/83] Add push notif implementation
---
.../notifications/PushNotifications.tsx | 211 ++++++++++++++++++
1 file changed, 211 insertions(+)
create mode 100644 src/app/features/settings/notifications/PushNotifications.tsx
diff --git a/src/app/features/settings/notifications/PushNotifications.tsx b/src/app/features/settings/notifications/PushNotifications.tsx
new file mode 100644
index 000000000..75b830efb
--- /dev/null
+++ b/src/app/features/settings/notifications/PushNotifications.tsx
@@ -0,0 +1,211 @@
+import { MatrixClient, PushRuleActionName, PushRuleKind, TweakName } from 'matrix-js-sdk';
+import { ClientConfig } from '../../../hooks/useClientConfig';
+
+export async function requestBrowserNotificationPermission(): Promise {
+ if (!('Notification' in window)) {
+ return 'denied';
+ }
+ try {
+ const permission: NotificationPermission = await Notification.requestPermission();
+ return permission;
+ } catch (error) {
+ return 'denied';
+ }
+}
+
+export async function enablePushNotifications(
+ mx: MatrixClient,
+ clientConfig: ClientConfig
+): Promise {
+ if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
+ throw new Error('Push messaging is not supported in this browser.');
+ }
+ if (!mx || !mx.getHomeserverUrl() || !mx.getAccessToken()) {
+ throw new Error('Matrix client is not properly initialized or authenticated.');
+ }
+
+ if (
+ !clientConfig.pushNotificationDetails?.vapidPublicKey ||
+ !clientConfig.pushNotificationDetails?.webPushAppID ||
+ !clientConfig.pushNotificationDetails?.pushNotifyUrl
+ ) {
+ throw new Error('One or more push configuration constants are missing.');
+ }
+
+ const registration = await navigator.serviceWorker.ready;
+
+ let subscription = await registration.pushManager.getSubscription();
+ if (!subscription) {
+ try {
+ subscription = await registration.pushManager.subscribe({
+ userVisibleOnly: true,
+ applicationServerKey: clientConfig.pushNotificationDetails?.vapidPublicKey,
+ });
+ } catch (subscribeError: any) {
+ if (Notification.permission === 'denied') {
+ throw new Error('Notification permission denied. Please enable in browser settings.');
+ }
+ throw new Error(`Failed to subscribe: ${subscribeError.message || String(subscribeError)}`);
+ }
+ }
+
+ const pwaAppIdForPlatform = clientConfig.pushNotificationDetails?.webPushAppID;
+ if (!pwaAppIdForPlatform) {
+ await subscription.unsubscribe();
+ throw new Error('Could not determine PWA App ID for push endpoint.');
+ }
+
+ const subJson = subscription.toJSON();
+ const p256dhKey = subJson.keys?.p256dh;
+ const authKey = subJson.keys?.auth;
+
+ if (!p256dhKey || !authKey) {
+ await subscription.unsubscribe();
+ throw new Error('Push subscription keys (p256dh, auth) are missing.');
+ }
+
+ const pusherData = {
+ kind: 'http' as const,
+ app_id: pwaAppIdForPlatform,
+ pushkey: p256dhKey,
+ app_display_name: 'Cinny',
+ device_display_name:
+ (await mx.getDevice(mx.getDeviceId() ?? '')).display_name ?? 'Unknown device',
+ lang: navigator.language || 'en',
+ data: {
+ url: clientConfig.pushNotificationDetails?.pushNotifyUrl,
+ format: 'event_id_only' as const,
+ endpoint: subscription.endpoint,
+ p256dh: p256dhKey,
+ auth: authKey,
+ },
+ enabled: false,
+ 'org.matrix.msc3881.enabled': false,
+ 'org.matrix.msc3881.device_id': mx.getDeviceId(),
+ append: false,
+ };
+
+ try {
+ await mx.setPusher(pusherData);
+ } catch (pusherError: any) {
+ await subscription.unsubscribe();
+ throw new Error(
+ `Failed to set up push with Matrix server: ${pusherError.message || String(pusherError)}`
+ );
+ }
+}
+
+export async function disablePushNotifications(
+ mx: MatrixClient,
+ clientConfig: ClientConfig
+): Promise {
+ if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
+ return;
+ }
+
+ const registration = await navigator.serviceWorker.ready;
+ const subscription = await registration.pushManager.getSubscription();
+
+ if (!subscription) {
+ return;
+ }
+
+ const pwaAppIdForPlatform = clientConfig.pushNotificationDetails?.webPushAppID;
+
+ await subscription.unsubscribe();
+
+ const subJson = subscription.toJSON();
+ const p256dhKey = subJson.keys?.p256dh;
+ const authKey = subJson.keys?.auth;
+
+ if (mx && mx.getAccessToken() && pwaAppIdForPlatform) {
+ const pusherToRemove = {
+ kind: null,
+ app_id: pwaAppIdForPlatform,
+ pushkey: p256dhKey,
+ };
+ await mx.setPusher(pusherToRemove as any);
+ }
+}
+
+export async function deRegisterAllPushers(mx: MatrixClient): Promise {
+ const response = await mx.getPushers();
+ const pushers = response.pushers || [];
+
+ if (pushers.length === 0) {
+ return;
+ }
+
+ const deletionPromises = pushers.map((pusher) => {
+ const pusherToDelete: Partial & { kind: null; app_id: string; pushkey: string } = {
+ kind: null,
+ app_id: pusher.app_id,
+ pushkey: pusher.pushkey,
+ ...(pusher.data && { data: pusher.data }),
+ ...(pusher.profile_tag && { profile_tag: pusher.profile_tag }),
+ };
+
+ return mx
+ .setPusher(pusherToDelete as any)
+ .then(() => ({ status: 'fulfilled', app_id: pusher.app_id }))
+ .catch((err) => ({ status: 'rejected', app_id: pusher.app_id, error: err }));
+ });
+
+ await Promise.allSettled(deletionPromises);
+}
+
+export async function togglePusher(
+ mx: MatrixClient,
+ subscription: PushSubscription,
+ visible: boolean
+): Promise {
+ const MUTE_RULE_ID = 'cc.cinny.mute_push';
+ const p256dhKey = subscription?.toJSON().keys?.p256dh;
+ const { pushers } = await mx.getPushers();
+ const existingPusher = pushers.find((p) => p.pushkey === p256dhKey);
+
+ if (existingPusher && existingPusher.kind === 'http') {
+ if (visible) {
+ /*
+ Need to clean up the old push rules I made
+ The push rules should be removed upon roomId change
+ and a new one added for the NEW current room
+
+ On visibility change push rule should be added for the given room
+ so in background pushrule removed and in foreground pushrule added
+
+ In some ways it is simply easier to just de-register the push notificaitons
+ as this gives perfect behavior. Then on visibility change re-enable them.
+ We can check the stored setting for background push notifs and if it exists
+ enable the push notifs based on that settings value.
+ Can look to the SettingsNotifications for how the other settings are stored.
+
+ I might also want to mention that the reason I list the above
+ is explicitly BECAUSE otherwise we use both push notifs and the normal notifs
+
+ Tuwunnel fails to deserialize custom tweaks as a result of:
+ https://github.com/ruma/ruma/issues/368 <- related deserialization issue
+ https://github.com/serde-rs/serde/issues/1183 <- upstream for ruma for deserializing
+
+ Instead we'll do a hackier bypass, but only Cinny will acknowledge this as the client is responsible
+ for handling the sounds themselves. This is more or less a custom tweak still.
+ */
+ mx.addPushRule('global', PushRuleKind.Override, `${MUTE_RULE_ID}`, {
+ conditions: [],
+ actions: [
+ PushRuleActionName.DontNotify,
+ {
+ set_tweak: TweakName.Sound,
+ value: 'cinny_show_banner',
+ },
+ {
+ set_tweak: TweakName.Highlight,
+ value: true,
+ },
+ ],
+ });
+ } else {
+ await mx.deletePushRule('global', PushRuleKind.Override, `${MUTE_RULE_ID}`);
+ }
+ }
+}
From af705f6785394af81314bda8d55d9f1064f63847 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:46:31 -0500
Subject: [PATCH 22/83] add push notif details to client config
---
src/app/hooks/useClientConfig.ts | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/src/app/hooks/useClientConfig.ts b/src/app/hooks/useClientConfig.ts
index e5fc6cc61..4e9fb7493 100644
--- a/src/app/hooks/useClientConfig.ts
+++ b/src/app/hooks/useClientConfig.ts
@@ -10,6 +10,12 @@ export type ClientConfig = {
homeserverList?: string[];
allowCustomHomeservers?: boolean;
+ pushNotificationDetails?: {
+ pushNotifyUrl?: string;
+ vapidPublicKey?: string;
+ webPushAppID?: string;
+ };
+
featuredCommunities?: {
openAsDefault?: boolean;
spaces?: string[];
From 758740302370d9b7af4cb5fb64fac50fd6c388e8 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:48:43 -0500
Subject: [PATCH 23/83] Update gitignore
---
.gitignore | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/.gitignore b/.gitignore
index 1af58a970..d08837374 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,4 +4,6 @@ node_modules
devAssets
.DS_Store
-.idea
\ No newline at end of file
+.idea
+
+.env
\ No newline at end of file
From 99891765b7ad2f79f483566a9b197ffb9786cd9f Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Sun, 8 Jun 2025 20:49:15 -0500
Subject: [PATCH 24/83] update package-lock
---
package-lock.json | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/package-lock.json b/package-lock.json
index 6d82c219d..9b5601c59 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -102,7 +102,8 @@
"vite": "5.4.15",
"vite-plugin-pwa": "0.20.5",
"vite-plugin-static-copy": "1.0.4",
- "vite-plugin-top-level-await": "1.4.4"
+ "vite-plugin-top-level-await": "1.4.4",
+ "workbox-precaching": "7.3.0"
},
"engines": {
"node": ">=16.0.0"
@@ -12212,6 +12213,7 @@
"resolved": "https://registry.npmjs.org/workbox-precaching/-/workbox-precaching-7.3.0.tgz",
"integrity": "sha512-ckp/3t0msgXclVAYaNndAGeAoWQUv7Rwc4fdhWL69CCAb2UHo3Cef0KIUctqfQj1p8h6aGyz3w8Cy3Ihq9OmIw==",
"dev": true,
+ "license": "MIT",
"dependencies": {
"workbox-core": "7.3.0",
"workbox-routing": "7.3.0",
From 39fa3c49b1f9415e5ef42b9fc2dcbee68f729c9b Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Tue, 10 Jun 2025 17:32:30 -0500
Subject: [PATCH 25/83] Undo these
---
src/app/pages/client/ClientNonUIFeatures.tsx | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx
index 0e2d5d678..170bc03be 100644
--- a/src/app/pages/client/ClientNonUIFeatures.tsx
+++ b/src/app/pages/client/ClientNonUIFeatures.tsx
@@ -187,15 +187,13 @@ function MessageNotifications() {
) => {
if (mx.getSyncState() !== 'SYNCING') return;
if (document.hasFocus() && (selectedRoomId === room?.roomId || notificationSelected)) return;
- let pushActions = mx.getPushActionsForEvent(mEvent);
- const hasInAppTweak = pushActions?.tweaks?.sound === 'cinny_show_banner';
if (
!room ||
!data.liveEvent ||
room.isSpaceRoom() ||
!isNotificationEvent(mEvent) ||
- (getNotificationType(mx, room.roomId) === NotificationType.Mute && !hasInAppTweak)
+ getNotificationType(mx, room.roomId) === NotificationType.Mute
) {
return;
}
From 91d6a5d2e91cb2fa8dceabdc8486702693cc9bd2 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Tue, 10 Jun 2025 17:35:58 -0500
Subject: [PATCH 26/83] Pass client config for togglePusher
---
src/app/pages/client/ClientRoot.tsx | 11 ++++++-----
1 file changed, 6 insertions(+), 5 deletions(-)
diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx
index 8eac63bd2..9f9341a4e 100644
--- a/src/app/pages/client/ClientRoot.tsx
+++ b/src/app/pages/client/ClientRoot.tsx
@@ -38,6 +38,7 @@ import { useSyncState } from '../../hooks/useSyncState';
import { stopPropagation } from '../../utils/keyboard';
import { SyncStatus } from './SyncStatus';
import { togglePusher } from '../../features/settings/notifications/PushNotifications';
+import { ClientConfig, useClientConfig } from '../../hooks/useClientConfig';
function ClientRootLoading() {
return (
@@ -125,12 +126,11 @@ function ClientRootOptions({ mx }: { mx?: MatrixClient }) {
);
}
-const pushNotificationListener = (mx: MatrixClient) => {
+const pushNotificationListener = (mx: MatrixClient, clientConfig: ClientConfig) => {
navigator.serviceWorker.ready.then((registration) => {
registration.pushManager.getSubscription().then((subscription) => {
document.addEventListener('visibilitychange', () => {
- console.log('Check check baby');
- togglePusher(mx, subscription, document.visibilityState === 'visible');
+ togglePusher(mx, subscription, clientConfig, document.visibilityState === 'visible');
});
togglePusher(mx, subscription, true);
});
@@ -159,6 +159,7 @@ type ClientRootProps = {
export function ClientRoot({ children }: ClientRootProps) {
const [loading, setLoading] = useState(true);
const { baseUrl } = getSecret();
+ const clientConfig = useClientConfig();
const [loadState, loadMatrix] = useAsyncCallback(
useCallback(() => initClient(getSecret() as any), [])
@@ -188,10 +189,10 @@ export function ClientRoot({ children }: ClientRootProps) {
(state) => {
if (state === 'PREPARED') {
setLoading(false);
- pushNotificationListener(mx);
+ pushNotificationListener(mx, clientConfig);
}
},
- [mx]
+ [clientConfig, mx]
)
);
return (
From f100279e650a4e504701575d083294a44ce12613 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Tue, 10 Jun 2025 17:37:54 -0500
Subject: [PATCH 27/83] Move message listener and add a togglePush listener
(should ensure registers/deregisters always go off this way)
---
src/sw.ts | 35 +++++++++++++++++++++++------------
1 file changed, 23 insertions(+), 12 deletions(-)
diff --git a/src/sw.ts b/src/sw.ts
index ac86f6222..c62d560af 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -19,18 +19,6 @@ function sendAndWaitForReply(client: WindowClient, type: string, payload: object
return promise;
}
-self.addEventListener('message', (event: ExtendableMessageEvent) => {
- const { replyTo } = event.data;
- if (replyTo) {
- const resolve = pendingReplies.get(replyTo);
- if (resolve) {
- pendingReplies.delete(replyTo);
- resolve(event.data.payload);
- }
- }
-});
-
-
function fetchConfig(token?: string): RequestInit | undefined {
if (!token) return undefined;
@@ -42,6 +30,29 @@ function fetchConfig(token?: string): RequestInit | undefined {
};
}
+self.addEventListener('message', (event: ExtendableMessageEvent) => {
+ if (event.data.type === 'togglePush') {
+ const token = event.data?.token;
+ const fetchOptions = fetchConfig(token);
+ event.waitUntil(
+ fetch(`${event.data.url}/_matrix/client/v3/pushers/set`, {
+ method: 'POST',
+ ...fetchOptions,
+ body: JSON.stringify(event.data.pusherData),
+ })
+ );
+ return;
+ }
+ const { replyTo } = event.data;
+ if (replyTo) {
+ const resolve = pendingReplies.get(replyTo);
+ if (resolve) {
+ pendingReplies.delete(replyTo);
+ resolve(event.data.payload);
+ }
+ }
+});
+
self.addEventListener('activate', (event: ExtendableEvent) => {
event.waitUntil(
(async () => {
From 07e15e2421fd076dddf08a7266763a5f88755aae Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Tue, 10 Jun 2025 17:39:45 -0500
Subject: [PATCH 28/83] Revise our fetch to be more in line with W3C spec
---
src/sw.ts | 12 ++++++++++--
1 file changed, 10 insertions(+), 2 deletions(-)
diff --git a/src/sw.ts b/src/sw.ts
index c62d560af..3fd25134d 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -76,13 +76,21 @@ self.addEventListener('fetch', (event: FetchEvent) => {
}
event.respondWith(
(async (): Promise => {
- console.log('Unironic race condition mitigation it seems.');
+ if (!event.clientId) throw new Error('Missing clientId');
const client = await self.clients.get(event.clientId);
- const token: string = await sendAndWaitForReply(client, 'token', {});
+ if (!client) throw new Error('Client not found');
+ const token = await sendAndWaitForReply(client, 'token', {});
+ if (!token) throw new Error('Failed to retrieve token');
const response = await fetch(url, fetchConfig(token));
+ if (!response.ok) throw new Error(`Fetch failed: ${response.statusText}`);
return response;
})()
);
+ event.waitUntil(
+ (async function () {
+ console.log('Ensuring fetch processing completes before worker termination.');
+ })()
+ );
});
const onPushNotification = async (event: PushEvent) => {
From 0c67cb40d728a6496f36346081275aedd9ffdcec Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Tue, 10 Jun 2025 17:40:56 -0500
Subject: [PATCH 29/83] Swap to sending to service worker for completion
---
.../notifications/PushNotifications.tsx | 18 +++++++++++++++---
1 file changed, 15 insertions(+), 3 deletions(-)
diff --git a/src/app/features/settings/notifications/PushNotifications.tsx b/src/app/features/settings/notifications/PushNotifications.tsx
index 75b830efb..adcb39eb2 100644
--- a/src/app/features/settings/notifications/PushNotifications.tsx
+++ b/src/app/features/settings/notifications/PushNotifications.tsx
@@ -86,7 +86,13 @@ export async function enablePushNotifications(
};
try {
- await mx.setPusher(pusherData);
+
+ navigator.serviceWorker.controller?.postMessage({
+ url: mx.baseUrl,
+ type: 'togglePush',
+ pusherData,
+ token: mx.getAccessToken(),
+ });
} catch (pusherError: any) {
await subscription.unsubscribe();
throw new Error(
@@ -119,12 +125,18 @@ export async function disablePushNotifications(
const authKey = subJson.keys?.auth;
if (mx && mx.getAccessToken() && pwaAppIdForPlatform) {
- const pusherToRemove = {
+ const pusherData = {
kind: null,
app_id: pwaAppIdForPlatform,
pushkey: p256dhKey,
};
- await mx.setPusher(pusherToRemove as any);
+
+ navigator.serviceWorker.controller?.postMessage({
+ url: mx.baseUrl,
+ type: 'togglePush',
+ pusherData,
+ token: mx.getAccessToken(),
+ });
}
}
From 129599572de43c1dc2c79b4bfb6a13523d74df37 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Tue, 10 Jun 2025 17:42:11 -0500
Subject: [PATCH 30/83] add client config to parameters
---
src/app/features/settings/notifications/PushNotifications.tsx | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/app/features/settings/notifications/PushNotifications.tsx b/src/app/features/settings/notifications/PushNotifications.tsx
index adcb39eb2..f3f6205cb 100644
--- a/src/app/features/settings/notifications/PushNotifications.tsx
+++ b/src/app/features/settings/notifications/PushNotifications.tsx
@@ -169,6 +169,7 @@ export async function deRegisterAllPushers(mx: MatrixClient): Promise {
export async function togglePusher(
mx: MatrixClient,
subscription: PushSubscription,
+ clientConfig: ClientConfig,
visible: boolean
): Promise {
const MUTE_RULE_ID = 'cc.cinny.mute_push';
From a02a10eda117b9a4d4353cf70dba221b1c591107 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Tue, 10 Jun 2025 17:43:18 -0500
Subject: [PATCH 31/83] adjust to reflect using the service worker to actually
toggle
---
.../notifications/PushNotifications.tsx | 25 ++++---------------
1 file changed, 5 insertions(+), 20 deletions(-)
diff --git a/src/app/features/settings/notifications/PushNotifications.tsx b/src/app/features/settings/notifications/PushNotifications.tsx
index f3f6205cb..6b02e7c00 100644
--- a/src/app/features/settings/notifications/PushNotifications.tsx
+++ b/src/app/features/settings/notifications/PushNotifications.tsx
@@ -177,9 +177,8 @@ export async function togglePusher(
const { pushers } = await mx.getPushers();
const existingPusher = pushers.find((p) => p.pushkey === p256dhKey);
- if (existingPusher && existingPusher.kind === 'http') {
- if (visible) {
- /*
+ if (visible) {
+ /*
Need to clean up the old push rules I made
The push rules should be removed upon roomId change
and a new one added for the NEW current room
@@ -203,22 +202,8 @@ export async function togglePusher(
Instead we'll do a hackier bypass, but only Cinny will acknowledge this as the client is responsible
for handling the sounds themselves. This is more or less a custom tweak still.
*/
- mx.addPushRule('global', PushRuleKind.Override, `${MUTE_RULE_ID}`, {
- conditions: [],
- actions: [
- PushRuleActionName.DontNotify,
- {
- set_tweak: TweakName.Sound,
- value: 'cinny_show_banner',
- },
- {
- set_tweak: TweakName.Highlight,
- value: true,
- },
- ],
- });
- } else {
- await mx.deletePushRule('global', PushRuleKind.Override, `${MUTE_RULE_ID}`);
- }
+ disablePushNotifications(mx, clientConfig);
+ } else {
+ enablePushNotifications(mx, clientConfig);
}
}
From 13d38e852551cd7b320cac84a04e2f1902ed4522 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Tue, 10 Jun 2025 17:43:27 -0500
Subject: [PATCH 32/83] Fix imports
---
src/app/features/settings/notifications/PushNotifications.tsx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/app/features/settings/notifications/PushNotifications.tsx b/src/app/features/settings/notifications/PushNotifications.tsx
index 6b02e7c00..aeb9e8094 100644
--- a/src/app/features/settings/notifications/PushNotifications.tsx
+++ b/src/app/features/settings/notifications/PushNotifications.tsx
@@ -1,4 +1,4 @@
-import { MatrixClient, PushRuleActionName, PushRuleKind, TweakName } from 'matrix-js-sdk';
+import { MatrixClient } from 'matrix-js-sdk';
import { ClientConfig } from '../../../hooks/useClientConfig';
export async function requestBrowserNotificationPermission(): Promise {
From c57509ac7b4ce99d34f758f21980d1e8cbaa433c Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Tue, 10 Jun 2025 17:45:23 -0500
Subject: [PATCH 33/83] Remove large comment block, no longer needed
---
.../notifications/PushNotifications.tsx | 31 -------------------
1 file changed, 31 deletions(-)
diff --git a/src/app/features/settings/notifications/PushNotifications.tsx b/src/app/features/settings/notifications/PushNotifications.tsx
index aeb9e8094..1aa8d2e2b 100644
--- a/src/app/features/settings/notifications/PushNotifications.tsx
+++ b/src/app/features/settings/notifications/PushNotifications.tsx
@@ -86,7 +86,6 @@ export async function enablePushNotifications(
};
try {
-
navigator.serviceWorker.controller?.postMessage({
url: mx.baseUrl,
type: 'togglePush',
@@ -168,40 +167,10 @@ export async function deRegisterAllPushers(mx: MatrixClient): Promise {
export async function togglePusher(
mx: MatrixClient,
- subscription: PushSubscription,
clientConfig: ClientConfig,
visible: boolean
): Promise {
- const MUTE_RULE_ID = 'cc.cinny.mute_push';
- const p256dhKey = subscription?.toJSON().keys?.p256dh;
- const { pushers } = await mx.getPushers();
- const existingPusher = pushers.find((p) => p.pushkey === p256dhKey);
-
if (visible) {
- /*
- Need to clean up the old push rules I made
- The push rules should be removed upon roomId change
- and a new one added for the NEW current room
-
- On visibility change push rule should be added for the given room
- so in background pushrule removed and in foreground pushrule added
-
- In some ways it is simply easier to just de-register the push notificaitons
- as this gives perfect behavior. Then on visibility change re-enable them.
- We can check the stored setting for background push notifs and if it exists
- enable the push notifs based on that settings value.
- Can look to the SettingsNotifications for how the other settings are stored.
-
- I might also want to mention that the reason I list the above
- is explicitly BECAUSE otherwise we use both push notifs and the normal notifs
-
- Tuwunnel fails to deserialize custom tweaks as a result of:
- https://github.com/ruma/ruma/issues/368 <- related deserialization issue
- https://github.com/serde-rs/serde/issues/1183 <- upstream for ruma for deserializing
-
- Instead we'll do a hackier bypass, but only Cinny will acknowledge this as the client is responsible
- for handling the sounds themselves. This is more or less a custom tweak still.
- */
disablePushNotifications(mx, clientConfig);
} else {
enablePushNotifications(mx, clientConfig);
From b148cc3d1b8007206f8ffc8d3fd10b9efbff87ef Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Tue, 10 Jun 2025 17:46:27 -0500
Subject: [PATCH 34/83] Remove subscription / service worker check requirement
---
src/app/pages/client/ClientRoot.tsx | 9 ++-------
1 file changed, 2 insertions(+), 7 deletions(-)
diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx
index 9f9341a4e..3d9c2b50f 100644
--- a/src/app/pages/client/ClientRoot.tsx
+++ b/src/app/pages/client/ClientRoot.tsx
@@ -127,13 +127,8 @@ function ClientRootOptions({ mx }: { mx?: MatrixClient }) {
}
const pushNotificationListener = (mx: MatrixClient, clientConfig: ClientConfig) => {
- navigator.serviceWorker.ready.then((registration) => {
- registration.pushManager.getSubscription().then((subscription) => {
- document.addEventListener('visibilitychange', () => {
- togglePusher(mx, subscription, clientConfig, document.visibilityState === 'visible');
- });
- togglePusher(mx, subscription, true);
- });
+ document.addEventListener('visibilitychange', () => {
+ togglePusher(mx, clientConfig, document.visibilityState === 'visible');
});
};
From 654f32bd31f6e578ea120620307a9308d2934786 Mon Sep 17 00:00:00 2001
From: Gigiaj
Date: Tue, 10 Jun 2025 19:23:51 -0500
Subject: [PATCH 35/83] Add store to push notif setting to local storage (so we
can manage the pusher state cleanly)
---
.../notifications/SystemNotification.tsx | 66 +++++--------------
1 file changed, 17 insertions(+), 49 deletions(-)
diff --git a/src/app/features/settings/notifications/SystemNotification.tsx b/src/app/features/settings/notifications/SystemNotification.tsx
index 6e292dd80..e0da07c06 100644
--- a/src/app/features/settings/notifications/SystemNotification.tsx
+++ b/src/app/features/settings/notifications/SystemNotification.tsx
@@ -1,5 +1,6 @@
import React, { useCallback, useEffect, useState } from 'react';
import { Box, Text, Switch, Button, color, Spinner } from 'folds';
+import { IPusherRequest } from 'matrix-js-sdk';
import { SequenceCard } from '../../../components/sequence-card';
import { SequenceCardStyle } from '../styles.css';
import { SettingTile } from '../../../components/setting-tile';
@@ -92,59 +93,30 @@ function EmailNotification() {
function WebPushNotificationSetting() {
const mx = useMatrixClient();
const clientConfig = useClientConfig();
- const [userWantsWebPush, setUserWantsWebPush] = useSetting(settingsAtom, 'enableWebPush');
-
+ const [userPushPreference, setUserPushPreference] = useState(false);
+ const [isLoading, setIsLoading] = useState(true);
const browserPermission = usePermissionState('notifications', getNotificationState());
- const [isPushSubscribed, setIsPushSubscribed] = useState(false);
- const [isLoading, setIsLoading] = useState(true); // Start loading to check status
-
- const checkSubscriptionStatus = useCallback(async () => {
- if (
- browserPermission === 'granted' &&
- 'serviceWorker' in navigator &&
- 'PushManager' in window
- ) {
- setIsLoading(true);
- try {
- const registration = await navigator.serviceWorker.ready;
- const subscription = await registration.pushManager.getSubscription();
- setIsPushSubscribed(!!subscription);
- } catch (err) {
- setIsPushSubscribed(false);
- } finally {
- setIsLoading(false);
- }
- } else {
- setIsPushSubscribed(false);
- setIsLoading(false);
- }
- }, [browserPermission]);
-
useEffect(() => {
- checkSubscriptionStatus();
- }, [checkSubscriptionStatus]);
-
+ const storedPreference = localStorage.getItem(PUSH_PREFERENCE_KEY);
+ setUserPushPreference(storedPreference === 'true');
+ setIsLoading(false);
+ }, []);
const handleRequestPermissionAndEnable = async () => {
setIsLoading(true);
try {
const permissionResult = await requestBrowserNotificationPermission();
if (permissionResult === 'granted') {
- setUserWantsWebPush(true);
await enablePushNotifications(mx, clientConfig);
- } else {
- setUserWantsWebPush(false);
+ localStorage.setItem('cinny_web_push_enabled', 'true');
+ setUserPushPreference(true);
}
- } catch (error: any) {
- setUserWantsWebPush(false);
} finally {
- await checkSubscriptionStatus();
setIsLoading(false);
}
};
const handlePushSwitchChange = async (wantsPush: boolean) => {
setIsLoading(true);
- setUserWantsWebPush(wantsPush);
try {
if (wantsPush) {
@@ -152,30 +124,23 @@ function WebPushNotificationSetting() {
} else {
await disablePushNotifications(mx, clientConfig);
}
- } catch (error: any) {
- setUserWantsWebPush(!wantsPush);
+ localStorage.setItem('cinny_web_push_enabled', String(wantsPush));
+ setUserPushPreference(wantsPush);
} finally {
- await checkSubscriptionStatus();
setIsLoading(false);
}
};
- let descriptionText = 'Receive notifications when the app is closed or in the background.';
- if (browserPermission === 'granted' && isPushSubscribed) {
- descriptionText =
- 'You are subscribed to receive notifications when the app is in the background.';
- }
-
return (
- Notification permission is blocked by your browser. Please allow it from site settings.
+ Permission blocked. Please allow notifications in your browser settings.
) : (
- {descriptionText}
+ 'Receive notifications when the app is closed or in the background.'
)
}
after={
@@ -186,7 +151,10 @@ function WebPushNotificationSetting() {
Enable
) : browserPermission === 'granted' ? (
-
+
) : null
}
/>
From b8eb1b999e00c510ed8b0e02cd21447b2e2bcfc0 Mon Sep 17 00:00:00 2001
From: Ajay Bura <32841439+ajbura@users.noreply.github.com>
Date: Tue, 10 Jun 2025 10:14:17 +0530
Subject: [PATCH 36/83] Fix space navigation & view space timeline dev-option
(#2358)
* fix inaccessible space on alias change
* fix new room in space open in home
* allow opening space timeline
* hide event timeline feature behind dev tool
* add navToActivePath to clear cache function
---
src/app/hooks/useRoomNavigate.ts | 16 ++++++--
src/app/pages/client/sidebar/SpaceTabs.tsx | 5 ++-
src/app/pages/client/space/RoomProvider.tsx | 45 ++++++++++++++++-----
src/app/pages/client/space/Space.tsx | 20 +++++++++
src/app/state/navToActivePath.ts | 8 +++-
src/client/initMatrix.ts | 2 +
6 files changed, 81 insertions(+), 15 deletions(-)
diff --git a/src/app/hooks/useRoomNavigate.ts b/src/app/hooks/useRoomNavigate.ts
index 0f9f365cd..e626c06bf 100644
--- a/src/app/hooks/useRoomNavigate.ts
+++ b/src/app/hooks/useRoomNavigate.ts
@@ -13,6 +13,8 @@ import { getOrphanParents } from '../utils/room';
import { roomToParentsAtom } from '../state/room/roomToParents';
import { mDirectAtom } from '../state/mDirectList';
import { useSelectedSpace } from './router/useSelectedSpace';
+import { settingsAtom } from '../state/settings';
+import { useSetting } from '../state/hooks/settings';
export const useRoomNavigate = () => {
const navigate = useNavigate();
@@ -20,6 +22,7 @@ export const useRoomNavigate = () => {
const roomToParents = useAtomValue(roomToParentsAtom);
const mDirects = useAtomValue(mDirectAtom);
const spaceSelectedId = useSelectedSpace();
+ const [developerTools] = useSetting(settingsAtom, 'developerTools');
const navigateSpace = useCallback(
(roomId: string) => {
@@ -32,15 +35,22 @@ export const useRoomNavigate = () => {
const navigateRoom = useCallback(
(roomId: string, eventId?: string, opts?: NavigateOptions) => {
const roomIdOrAlias = getCanonicalAliasOrRoomId(mx, roomId);
+ const openSpaceTimeline = developerTools && spaceSelectedId === roomId;
- const orphanParents = getOrphanParents(roomToParents, roomId);
+ const orphanParents = openSpaceTimeline ? [roomId] : getOrphanParents(roomToParents, roomId);
if (orphanParents.length > 0) {
const pSpaceIdOrAlias = getCanonicalAliasOrRoomId(
mx,
spaceSelectedId && orphanParents.includes(spaceSelectedId)
? spaceSelectedId
- : orphanParents[0]
+ : orphanParents[0] // TODO: better orphan parent selection.
);
+
+ if (openSpaceTimeline) {
+ navigate(getSpaceRoomPath(pSpaceIdOrAlias, roomId, eventId), opts);
+ return;
+ }
+
navigate(getSpaceRoomPath(pSpaceIdOrAlias, roomIdOrAlias, eventId), opts);
return;
}
@@ -52,7 +62,7 @@ export const useRoomNavigate = () => {
navigate(getHomeRoomPath(roomIdOrAlias, eventId), opts);
},
- [mx, navigate, spaceSelectedId, roomToParents, mDirects]
+ [mx, navigate, spaceSelectedId, roomToParents, mDirects, developerTools]
);
return {
diff --git a/src/app/pages/client/sidebar/SpaceTabs.tsx b/src/app/pages/client/sidebar/SpaceTabs.tsx
index 5b47cb52c..011741eee 100644
--- a/src/app/pages/client/sidebar/SpaceTabs.tsx
+++ b/src/app/pages/client/sidebar/SpaceTabs.tsx
@@ -744,13 +744,14 @@ export function SpaceTabs({ scrollRef }: SpaceTabsProps) {
const targetSpaceId = target.getAttribute('data-id');
if (!targetSpaceId) return;
+ const spacePath = getSpacePath(getCanonicalAliasOrRoomId(mx, targetSpaceId));
if (screenSize === ScreenSize.Mobile) {
- navigate(getSpacePath(getCanonicalAliasOrRoomId(mx, targetSpaceId)));
+ navigate(spacePath);
return;
}
const activePath = navToActivePath.get(targetSpaceId);
- if (activePath) {
+ if (activePath && activePath.pathname.startsWith(spacePath)) {
navigate(joinPathComponent(activePath));
return;
}
diff --git a/src/app/pages/client/space/RoomProvider.tsx b/src/app/pages/client/space/RoomProvider.tsx
index a96321374..0fd52ab67 100644
--- a/src/app/pages/client/space/RoomProvider.tsx
+++ b/src/app/pages/client/space/RoomProvider.tsx
@@ -1,21 +1,24 @@
import React, { ReactNode } from 'react';
import { useParams } from 'react-router-dom';
-import { useAtomValue } from 'jotai';
+import { useAtom, useAtomValue } from 'jotai';
import { useSelectedRoom } from '../../../hooks/router/useSelectedRoom';
import { IsDirectRoomProvider, RoomProvider } from '../../../hooks/useRoom';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { JoinBeforeNavigate } from '../../../features/join-before-navigate';
import { useSpace } from '../../../hooks/useSpace';
-import { getAllParents } from '../../../utils/room';
+import { getAllParents, getSpaceChildren } from '../../../utils/room';
import { roomToParentsAtom } from '../../../state/room/roomToParents';
import { allRoomsAtom } from '../../../state/room-list/roomList';
import { useSearchParamsViaServers } from '../../../hooks/router/useSearchParamsViaServers';
import { mDirectAtom } from '../../../state/mDirectList';
+import { settingsAtom } from '../../../state/settings';
+import { useSetting } from '../../../state/hooks/settings';
export function SpaceRouteRoomProvider({ children }: { children: ReactNode }) {
const mx = useMatrixClient();
const space = useSpace();
- const roomToParents = useAtomValue(roomToParentsAtom);
+ const [developerTools] = useSetting(settingsAtom, 'developerTools');
+ const [roomToParents, setRoomToParents] = useAtom(roomToParentsAtom);
const mDirects = useAtomValue(mDirectAtom);
const allRooms = useAtomValue(allRoomsAtom);
@@ -24,12 +27,36 @@ export function SpaceRouteRoomProvider({ children }: { children: ReactNode }) {
const roomId = useSelectedRoom();
const room = mx.getRoom(roomId);
- if (
- !room ||
- room.isSpaceRoom() ||
- !allRooms.includes(room.roomId) ||
- !getAllParents(roomToParents, room.roomId).has(space.roomId)
- ) {
+ if (!room || !allRooms.includes(room.roomId)) {
+ // room is not joined
+ return (
+
+ );
+ }
+
+ if (developerTools && room.isSpaceRoom() && room.roomId === space.roomId) {
+ // allow to view space timeline
+ return (
+
+ {children}
+
+ );
+ }
+
+ if (!getAllParents(roomToParents, room.roomId).has(space.roomId)) {
+ if (getSpaceChildren(space).includes(room.roomId)) {
+ // fill missing roomToParent mapping
+ setRoomToParents({
+ type: 'PUT',
+ parent: space.roomId,
+ children: [room.roomId],
+ });
+ }
+
return (
(({ room, requestClose }, ref) => {
const mx = useMatrixClient();
const [hideActivity] = useSetting(settingsAtom, 'hideActivity');
+ const [developerTools] = useSetting(settingsAtom, 'developerTools');
const roomToParents = useAtomValue(roomToParentsAtom);
const powerLevels = usePowerLevels(room);
const { getPowerLevel, canDoAction } = usePowerLevelsAPI(powerLevels);
const canInvite = canDoAction('invite', getPowerLevel(mx.getUserId() ?? ''));
const openSpaceSettings = useOpenSpaceSettings();
+ const { navigateRoom } = useRoomNavigate();
const allChild = useSpaceChildren(
allRoomsAtom,
@@ -118,6 +121,11 @@ const SpaceMenu = forwardRef(({ room, requestClo
requestClose();
};
+ const handleOpenTimeline = () => {
+ navigateRoom(room.roomId);
+ requestClose();
+ };
+
return (
} />
+ } />
join} />
} />
} />
} />
+ } />
} />
} />
+ } />
Page not found} />
diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx
index 5c00d7b63..04696949b 100644
--- a/src/app/pages/client/ClientNonUIFeatures.tsx
+++ b/src/app/pages/client/ClientNonUIFeatures.tsx
@@ -26,6 +26,7 @@ import { getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix';
import { useSelectedRoom } from '../../hooks/router/useSelectedRoom';
import { useInboxNotificationsSelected } from '../../hooks/router/useInbox';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
+import { useRoomNavigate } from '../../hooks/useRoomNavigate';
function SystemEmojiFeature() {
const [twitterEmoji] = useSetting(settingsAtom, 'twitterEmoji');
@@ -263,6 +264,41 @@ function MessageNotifications() {
);
}
+function HandleNotificationClick() {
+ const { navigateRoom } = useRoomNavigate();
+
+ const handleNotificationClickEvent = (event: any) => {
+ if (
+ !event.data ||
+ !event.source
+ ) {
+ return;
+ }
+ const eventData = event.data;
+ if (
+ !(eventData.type == "notificationToRoomEvent") ||
+ !eventData.room_id ||
+ !eventData.event_id
+ ) {
+ return;
+ }
+
+ console.log("main thread received notification click event:");
+ console.log(event);
+ navigateRoom(eventData.room_id, eventData.event_id);
+ };
+
+ useEffect( () => {
+ navigator.serviceWorker.addEventListener("message", handleNotificationClickEvent);
+ console.log("notification click event is listening on main thread");
+ return () => {
+ navigator.serviceWorker.removeEventListener("message", handleNotificationClickEvent);
+ }
+ }, [navigateRoom]);
+
+ return null;
+}
+
type ClientNonUIFeaturesProps = {
children: ReactNode;
};
@@ -275,6 +311,7 @@ export function ClientNonUIFeatures({ children }: ClientNonUIFeaturesProps) {
+
{children}
>
);
diff --git a/src/app/pages/client/ToRoomEvent.tsx b/src/app/pages/client/ToRoomEvent.tsx
new file mode 100644
index 000000000..6ca34c74c
--- /dev/null
+++ b/src/app/pages/client/ToRoomEvent.tsx
@@ -0,0 +1,16 @@
+import React, { useEffect } from "react";
+import { useParams } from "react-router-dom";
+import { useRoomNavigate } from "../../hooks/useRoomNavigate";
+
+export function ToRoomEvent() {
+ const { room_id, event_id } = useParams();
+ const { navigateRoom } = useRoomNavigate();
+
+ useEffect(() => {
+ if (!room_id) { return; }
+
+ navigateRoom(room_id, event_id);
+ }, [room_id, event_id, navigateRoom]);
+
+ return null;
+}
diff --git a/src/app/pages/paths.ts b/src/app/pages/paths.ts
index 54da89220..8aae52402 100644
--- a/src/app/pages/paths.ts
+++ b/src/app/pages/paths.ts
@@ -83,6 +83,9 @@ export type InboxNotificationsPathSearchParams = {
export const INBOX_NOTIFICATIONS_PATH = `/inbox/${_NOTIFICATIONS_PATH}`;
export const INBOX_INVITES_PATH = `/inbox/${_INVITES_PATH}`;
+export const _TO_PATH = '/to';
+export const TO_ROOM_EVENT_PATH = `${_TO_PATH}/:room_id/:event_id?`;
+
export const SPACE_SETTINGS_PATH = '/space-settings/';
export const ROOM_SETTINGS_PATH = '/room-settings/';
diff --git a/src/sw.ts b/src/sw.ts
index 0fc2e512c..3c6ffaace 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -135,7 +135,7 @@ const handlePushNotificationEventData = async (eventData: PushMessageData) => {
const pushData = eventData.json();
console.log(pushData); // TODO: delete this
- if (typeof pushData.unread === 'number') {
+ if (typeof pushData?.unread === 'number') {
try {
self.navigator.setAppBadge(pushData.unread);
} catch (e) {
@@ -146,15 +146,15 @@ const handlePushNotificationEventData = async (eventData: PushMessageData) => {
}
let title = undefined;
- if (pushData.sender_display_name && pushData.room_name) {
+ if (pushData?.sender_display_name && pushData?.room_name) {
title = `${pushData.sender_display_name} in ${pushData.room_name}`;
}
title = title ?? "New Notification";
let body = "You have a new message";
- if (pushData.content.ciphertext) {
+ if (pushData?.content?.ciphertext) {
body = `Encrypted message`;
- } else if (pushData.content.body) {
+ } else if (pushData?.content?.body) {
body = pushData.content.body;
} else {
return;
@@ -167,6 +167,8 @@ const handlePushNotificationEventData = async (eventData: PushMessageData) => {
data: {
url: self.registration.scope,
timestamp: Date.now(),
+ room_id: pushData.room_id,
+ event_id: pushData.event_id,
...pushData.data,
},
tag: "Cinny",
@@ -187,17 +189,24 @@ self.addEventListener('push', (event: PushEvent) => event.waitUntil(onPushNotifi
self.addEventListener('notificationclick', (event: NotificationEvent) => {
event.notification.close();
- /**
- * We should likely add a postMessage back to navigate to the room the event is from
- */
- // const targetUrl = event.notification.data?.url || self.registration.scope;
- const targetUrl = `${self.registration.scope}/inbox/notifications/`;
+ const messageData = event.notification.data;
+ const scope = self.registration.scope;
+ const targetUrl = (messageData?.room_id && messageData?.event_id)
+ ? `${scope}to/${messageData.room_id}/${messageData.event_id}`
+ : `${scope}inbox/notifications/`;
+ const postMessageToClient = (client: WindowClient) => {
+ client.postMessage({
+ type: "notificationToRoomEvent",
+ room_id: event.notification.data?.room_id,
+ event_id: event.notification.data?.event_id,
+ });
+ };
event.waitUntil(
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
for (const client of clientList) {
- if (client.url === targetUrl && 'focus' in client) {
- return (client as WindowClient).focus();
+ if ('focus' in client) {
+ return (client as WindowClient).focus().then(postMessageToClient);
}
}
if (self.clients.openWindow) {
From 6d962a64f9ca9bcb6c1ce8cfc638c7cc0f4ab363 Mon Sep 17 00:00:00 2001
From: Kris Hu
Date: Fri, 11 Jul 2025 19:58:09 +0800
Subject: [PATCH 68/83] avoid duplicated notification from push and in-app
still need to handle invitation notification
---
src/app/pages/client/ClientNonUIFeatures.tsx | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx
index 04696949b..42dbc4ff4 100644
--- a/src/app/pages/client/ClientNonUIFeatures.tsx
+++ b/src/app/pages/client/ClientNonUIFeatures.tsx
@@ -196,6 +196,7 @@ function MessageNotifications() {
data
) => {
if (mx.getSyncState() !== 'SYNCING') return;
+ if (document.visibilityState != "visible") return;
if (document.hasFocus() && (selectedRoomId === room?.roomId || notificationSelected)) return;
if (
From 10ef89ed3a9cc84660c2f57420d4e15a07c7efa7 Mon Sep 17 00:00:00 2001
From: Kris Hu
Date: Sat, 12 Jul 2025 16:22:58 +0800
Subject: [PATCH 69/83] close push notifications when all have been read
---
src/sw.ts | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/src/sw.ts b/src/sw.ts
index 3c6ffaace..15a554792 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -141,6 +141,13 @@ const handlePushNotificationEventData = async (eventData: PushMessageData) => {
} catch (e) {
// Likely Firefox/Gecko-based and doesn't support badging API
}
+ if (pushData.unread == 0) {
+ self.registration.getNotifications({ tag: "Cinny" })
+ .then((notifications) => notifications
+ .forEach((notification) => notification.close()));
+ await navigator.clearAppBadge();
+ return;
+ }
} else {
await navigator.clearAppBadge();
}
From 7083bff1139d91f6b7e1cae75d24522e1477589a Mon Sep 17 00:00:00 2001
From: Kris Hu
Date: Sun, 13 Jul 2025 20:26:55 +0800
Subject: [PATCH 70/83] feature(sw): add invitation support for push
notification
---
src/app/pages/client/ClientNonUIFeatures.tsx | 34 +++---
src/sw.ts | 102 ++++++++----------
src/sw/pushNotification.ts | 107 +++++++++++++++++++
3 files changed, 169 insertions(+), 74 deletions(-)
create mode 100644 src/sw/pushNotification.ts
diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx
index 42dbc4ff4..fa9a26ad3 100644
--- a/src/app/pages/client/ClientNonUIFeatures.tsx
+++ b/src/app/pages/client/ClientNonUIFeatures.tsx
@@ -119,6 +119,7 @@ function InviteNotifications() {
}, []);
useEffect(() => {
+ if (document.visibilityState != "visible") return;
if (invites.length > perviousInviteLen && mx.getSyncState() === 'SYNCING') {
if (showNotifications && notificationPermission('granted')) {
notify(invites.length - perviousInviteLen);
@@ -267,29 +268,34 @@ function MessageNotifications() {
function HandleNotificationClick() {
const { navigateRoom } = useRoomNavigate();
+ const navigate = useNavigate();
const handleNotificationClickEvent = (event: any) => {
if (
!event.data ||
!event.source
- ) {
- return;
- }
+ ) return;
const eventData = event.data;
- if (
- !(eventData.type == "notificationToRoomEvent") ||
- !eventData.room_id ||
- !eventData.event_id
- ) {
- return;
- }
+ if (!(eventData?.type == "notificationToRoomEvent")) return;
+ const messageData = eventData?.message;
+ if (!messageData) navigate(getInboxNotificationsPath());
- console.log("main thread received notification click event:");
- console.log(event);
- navigateRoom(eventData.room_id, eventData.event_id);
+ const eventType = messageData!.type as EventType;
+ switch (eventType) {
+ case EventType.RoomMessage:
+ case EventType.RoomMessageEncrypted:
+ navigateRoom(messageData!.room_id, messageData!.event_id);
+ return;
+ case EventType.RoomMember:
+ if (!(messageData?.content?.membership == "invite")) return;
+ navigate(getInboxInvitesPath());
+ return;
+ default:
+ return;
+ }
};
- useEffect( () => {
+ useEffect(() => {
navigator.serviceWorker.addEventListener("message", handleNotificationClickEvent);
console.log("notification click event is listening on main thread");
return () => {
diff --git a/src/sw.ts b/src/sw.ts
index 15a554792..7a95dd8c9 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -1,11 +1,12 @@
///
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
+import { usePushNotifications } from './sw/pushNotification';
+import { EventType } from 'matrix-js-sdk';
export type {};
declare const self: ServiceWorkerGlobalScope;
-const DEFAULT_NOTIFICATION_ICON = '/public/res/apple/apple-touch-icon-180x180.png';
-const DEFAULT_NOTIFICATION_BADGE = '/public/res/apple-touch-icon-72x72.png';
+const { handlePushNotificationPushData } = usePushNotifications(self);
const pendingReplies = new Map();
let messageIdCounter = 0;
@@ -131,64 +132,33 @@ self.addEventListener('fetch', (event: FetchEvent) => {
);
});
-const handlePushNotificationEventData = async (eventData: PushMessageData) => {
- const pushData = eventData.json();
- console.log(pushData); // TODO: delete this
-
- if (typeof pushData?.unread === 'number') {
- try {
- self.navigator.setAppBadge(pushData.unread);
- } catch (e) {
- // Likely Firefox/Gecko-based and doesn't support badging API
- }
- if (pushData.unread == 0) {
- self.registration.getNotifications({ tag: "Cinny" })
- .then((notifications) => notifications
- .forEach((notification) => notification.close()));
- await navigator.clearAppBadge();
- return;
- }
- } else {
- await navigator.clearAppBadge();
- }
-
- let title = undefined;
- if (pushData?.sender_display_name && pushData?.room_name) {
- title = `${pushData.sender_display_name} in ${pushData.room_name}`;
- }
- title = title ?? "New Notification";
-
- let body = "You have a new message";
- if (pushData?.content?.ciphertext) {
- body = `Encrypted message`;
- } else if (pushData?.content?.body) {
- body = pushData.content.body;
- } else {
- return;
- }
-
- self.registration.showNotification(title, {
- body: body,
- icon: DEFAULT_NOTIFICATION_ICON,
- badge: DEFAULT_NOTIFICATION_BADGE,
- data: {
- url: self.registration.scope,
- timestamp: Date.now(),
- room_id: pushData.room_id,
- event_id: pushData.event_id,
- ...pushData.data,
- },
- tag: "Cinny",
- silent: pushData.silent ?? false,
- });
-};
const onPushNotification = async (event: PushEvent) => {
- if (!event.data) {
+ if (!event?.data) {
return;
}
+ const pushData = event.data.json();
+ console.log(pushData);
- handlePushNotificationEventData(event.data);
+ try {
+ if (typeof pushData?.unread === 'number') {
+ self.navigator.setAppBadge(pushData.unread);
+
+ if (pushData.unread == 0) {
+ self.registration.getNotifications({ tag: "Cinny" })
+ .then((notifications) => notifications
+ .forEach((notification) => notification.close()));
+ await navigator.clearAppBadge();
+ return;
+ }
+ } else {
+ await navigator.clearAppBadge();
+ }
+ } catch (_) {
+ // Likely Firefox/Gecko-based and doesn't support badging API
+ }
+
+ handlePushNotificationPushData(pushData);
};
self.addEventListener('push', (event: PushEvent) => event.waitUntil(onPushNotification(event)));
@@ -198,14 +168,26 @@ self.addEventListener('notificationclick', (event: NotificationEvent) => {
const messageData = event.notification.data;
const scope = self.registration.scope;
- const targetUrl = (messageData?.room_id && messageData?.event_id)
- ? `${scope}to/${messageData.room_id}/${messageData.event_id}`
- : `${scope}inbox/notifications/`;
+
+ console.log(messageData);
+ const eventType = messageData?.type as (EventType | undefined);
+ if (!eventType) return Promise.resolve();
+
+ let targetUrl: string = `${scope}inbox/`;
+ if (
+ (eventType == EventType.RoomMessage || eventType == EventType.RoomMessageEncrypted) &&
+ messageData?.room_id && messageData?.event_id
+ ) targetUrl = `${scope}to/${messageData.room_id}/${messageData.event_id}`;
+ if (
+ eventType == EventType.RoomMember &&
+ messageData?.content?.membership == "invite"
+ ) targetUrl = `${scope}inbox/invites/`;
+ console.log(`target url = ${targetUrl}`);
+
const postMessageToClient = (client: WindowClient) => {
client.postMessage({
type: "notificationToRoomEvent",
- room_id: event.notification.data?.room_id,
- event_id: event.notification.data?.event_id,
+ message: messageData
});
};
diff --git a/src/sw/pushNotification.ts b/src/sw/pushNotification.ts
new file mode 100644
index 000000000..cbcd21b21
--- /dev/null
+++ b/src/sw/pushNotification.ts
@@ -0,0 +1,107 @@
+import { EventType } from "matrix-js-sdk";
+
+const DEFAULT_NOTIFICATION_ICON = '/public/res/apple/apple-touch-icon-180x180.png';
+const DEFAULT_NOTIFICATION_BADGE = '/public/res/apple-touch-icon-72x72.png';
+
+export const usePushNotifications = (self: ServiceWorkerGlobalScope) => {
+
+ const showNotificationWithData = async (
+ title: string,
+ body: string,
+ data: any,
+ silent: boolean = false
+ ) => {
+ await self.registration.showNotification(title, {
+ body,
+ icon: DEFAULT_NOTIFICATION_ICON,
+ badge: DEFAULT_NOTIFICATION_BADGE,
+ tag: "Cinny",
+ silent,
+ data
+ });
+ };
+
+ const handleRoomMessageNotification = async (pushData: any) => {
+ const title = pushData?.sender_display_name && pushData?.room_name
+ ? `${pushData.sender_display_name} in ${pushData.room_name}`
+ : "New Notification";
+ const body = pushData?.content?.body ?? "You have a new message";
+ const data = {
+ type: pushData!.type,
+ room_id: pushData!.room_id,
+ event_id: pushData!.event_id,
+ timestamp: Date.now(),
+ ...pushData.data
+ };
+ await showNotificationWithData(title, body, data, pushData.silent ?? false);
+ }
+
+ const handleEncryptedMessageNotification = async (pushData: any) => {
+ const title = pushData?.sender_display_name && pushData?.room_name
+ ? `${pushData.sender_display_name} in ${pushData.room_name}`
+ : "New Notification";
+ const body = "Encrypted message";
+ const data = {
+ type: pushData!.type,
+ room_id: pushData!.room_id,
+ event_id: pushData!.event_id,
+ timestamp: Date.now(),
+ ...pushData.data
+ };
+ await showNotificationWithData(title, body, data, pushData.silent ?? false);
+ }
+
+ const handleInvitationNotification = async (pushData: any) => {
+ const sender_display_name = pushData?.sender_display_name;
+ const room_name = pushData?.room_name;
+
+ let body: string = "";
+ if (sender_display_name && room_name)
+ body = `${sender_display_name} invites you to ${room_name}`;
+ if (sender_display_name && !room_name)
+ body = `from ${sender_display_name}`;
+ if (!sender_display_name && room_name)
+ body = `to ${room_name}`;
+ if (!sender_display_name && !room_name)
+ body = "";
+
+ const data = {
+ type: pushData!.type,
+ content: pushData!.content,
+ timestamp: Date.now(),
+ ...pushData.data
+ }
+
+ await showNotificationWithData(
+ "New Invitation",
+ body,
+ data
+ )
+ };
+
+ const handlePushNotificationPushData = async (pushData: any) => {
+ const eventType = pushData?.type as (EventType | undefined);
+ if (!eventType) {
+ console.log("no event type");
+ return;
+ }
+
+ switch (eventType) {
+ case EventType.RoomMessage:
+ await handleRoomMessageNotification(pushData);
+ return;
+ case EventType.RoomMessageEncrypted:
+ await handleEncryptedMessageNotification(pushData);
+ return;
+ case EventType.RoomMember:
+ if (!(pushData?.content?.membership == "invite")) return;
+ await handleInvitationNotification(pushData);
+ return;
+ default:
+ // no voip support in app anyway
+ return;
+ }
+ };
+
+ return { handlePushNotificationPushData };
+}
From 7151597888ee4fffbb402dc5f5a04493a7112c2a Mon Sep 17 00:00:00 2001
From: Kris Hu
Date: Mon, 14 Jul 2025 12:17:44 +0800
Subject: [PATCH 71/83] fix(notification): allow in-app notification in
background when push notification isn't enabled
---
src/app/pages/client/ClientNonUIFeatures.tsx | 18 +++++++++++++++---
1 file changed, 15 insertions(+), 3 deletions(-)
diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx
index fa9a26ad3..f9261df60 100644
--- a/src/app/pages/client/ClientNonUIFeatures.tsx
+++ b/src/app/pages/client/ClientNonUIFeatures.tsx
@@ -94,6 +94,7 @@ function InviteNotifications() {
const navigate = useNavigate();
const [showNotifications] = useSetting(settingsAtom, 'useInAppNotifications');
+ const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications');
const [notificationSound] = useSetting(settingsAtom, 'isNotificationSounds');
const notify = useCallback(
@@ -119,7 +120,7 @@ function InviteNotifications() {
}, []);
useEffect(() => {
- if (document.visibilityState != "visible") return;
+ if (usePushNotifications && document.visibilityState != "visible") return;
if (invites.length > perviousInviteLen && mx.getSyncState() === 'SYNCING') {
if (showNotifications && notificationPermission('granted')) {
notify(invites.length - perviousInviteLen);
@@ -129,7 +130,16 @@ function InviteNotifications() {
playSound();
}
}
- }, [mx, invites, perviousInviteLen, showNotifications, notificationSound, notify, playSound]);
+ }, [
+ mx,
+ invites,
+ perviousInviteLen,
+ showNotifications,
+ usePushNotifications,
+ notificationSound,
+ notify,
+ playSound
+ ]);
return (
// eslint-disable-next-line jsx-a11y/media-has-caption
@@ -146,6 +156,7 @@ function MessageNotifications() {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const [showNotifications] = useSetting(settingsAtom, 'useInAppNotifications');
+ const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications');
const [notificationSound] = useSetting(settingsAtom, 'isNotificationSounds');
const navigate = useNavigate();
@@ -197,7 +208,7 @@ function MessageNotifications() {
data
) => {
if (mx.getSyncState() !== 'SYNCING') return;
- if (document.visibilityState != "visible") return;
+ if (usePushNotifications && document.visibilityState != "visible") return;
if (document.hasFocus() && (selectedRoomId === room?.roomId || notificationSelected)) return;
if (
@@ -252,6 +263,7 @@ function MessageNotifications() {
notificationSound,
notificationSelected,
showNotifications,
+ usePushNotifications,
playSound,
notify,
selectedRoomId,
From 25d77d513244a19cf0cf7cf39bc48c2826cd5676 Mon Sep 17 00:00:00 2001
From: Kris Hu
Date: Mon, 14 Jul 2025 15:08:11 +0800
Subject: [PATCH 72/83] fix(push): use unique tag for push notifications
---
src/sw.ts | 4 ++--
src/sw/pushNotification.ts | 4 ++--
2 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/src/sw.ts b/src/sw.ts
index 7a95dd8c9..a58d60c8e 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -145,7 +145,7 @@ const onPushNotification = async (event: PushEvent) => {
self.navigator.setAppBadge(pushData.unread);
if (pushData.unread == 0) {
- self.registration.getNotifications({ tag: "Cinny" })
+ self.registration.getNotifications()
.then((notifications) => notifications
.forEach((notification) => notification.close()));
await navigator.clearAppBadge();
@@ -158,7 +158,7 @@ const onPushNotification = async (event: PushEvent) => {
// Likely Firefox/Gecko-based and doesn't support badging API
}
- handlePushNotificationPushData(pushData);
+ await handlePushNotificationPushData(pushData);
};
self.addEventListener('push', (event: PushEvent) => event.waitUntil(onPushNotification(event)));
diff --git a/src/sw/pushNotification.ts b/src/sw/pushNotification.ts
index cbcd21b21..f1331ff54 100644
--- a/src/sw/pushNotification.ts
+++ b/src/sw/pushNotification.ts
@@ -9,13 +9,13 @@ export const usePushNotifications = (self: ServiceWorkerGlobalScope) => {
title: string,
body: string,
data: any,
- silent: boolean = false
+ silent: boolean | null = null
) => {
await self.registration.showNotification(title, {
body,
icon: DEFAULT_NOTIFICATION_ICON,
badge: DEFAULT_NOTIFICATION_BADGE,
- tag: "Cinny",
+ tag: data?.event_id ?? "Cinny",
silent,
data
});
From 6abd8ff6bf2632bfcf0287d8a8840856a03c88a9 Mon Sep 17 00:00:00 2001
From: Kris Hu
Date: Mon, 14 Jul 2025 17:45:58 +0800
Subject: [PATCH 73/83] fix(to): load space list first
---
src/app/pages/client/ToRoomEvent.tsx | 19 +++++++++++++++++--
1 file changed, 17 insertions(+), 2 deletions(-)
diff --git a/src/app/pages/client/ToRoomEvent.tsx b/src/app/pages/client/ToRoomEvent.tsx
index 6ca34c74c..ebe1bef93 100644
--- a/src/app/pages/client/ToRoomEvent.tsx
+++ b/src/app/pages/client/ToRoomEvent.tsx
@@ -1,16 +1,31 @@
import React, { useEffect } from "react";
import { useParams } from "react-router-dom";
import { useRoomNavigate } from "../../hooks/useRoomNavigate";
+import { useMatrixClient } from "../../hooks/useMatrixClient";
+import { useAtomValue } from "jotai";
+import { roomToParentsAtom } from "../../state/room/roomToParents";
+import { mDirectAtom } from "../../state/mDirectList";
export function ToRoomEvent() {
+ const mx = useMatrixClient();
+ const roomToParents = useAtomValue(roomToParentsAtom);
+ const mDirects = useAtomValue(mDirectAtom);
const { room_id, event_id } = useParams();
const { navigateRoom } = useRoomNavigate();
useEffect(() => {
- if (!room_id) { return; }
+ if (!room_id || !mx) { return; }
+ if (!roomToParents.size || !mDirects.size) { return; }
navigateRoom(room_id, event_id);
- }, [room_id, event_id, navigateRoom]);
+ }, [
+ mx,
+ roomToParents,
+ mDirects,
+ room_id,
+ event_id,
+ navigateRoom
+ ]);
return null;
}
From 75816cf991e2ffef6891cfc92da8b17ee5f2af87 Mon Sep 17 00:00:00 2001
From: Kris Hu
Date: Mon, 14 Jul 2025 22:42:28 +0800
Subject: [PATCH 74/83] fix(sw): only import matrix sdk types
---
src/sw.ts | 2 +-
src/sw/pushNotification.ts | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/sw.ts b/src/sw.ts
index a58d60c8e..e9716e3ed 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -1,7 +1,7 @@
///
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
import { usePushNotifications } from './sw/pushNotification';
-import { EventType } from 'matrix-js-sdk';
+import { EventType } from "matrix-js-sdk/lib/@types/event";
export type {};
declare const self: ServiceWorkerGlobalScope;
diff --git a/src/sw/pushNotification.ts b/src/sw/pushNotification.ts
index f1331ff54..8e5073bca 100644
--- a/src/sw/pushNotification.ts
+++ b/src/sw/pushNotification.ts
@@ -1,4 +1,4 @@
-import { EventType } from "matrix-js-sdk";
+import { EventType } from "matrix-js-sdk/lib/@types/event";
const DEFAULT_NOTIFICATION_ICON = '/public/res/apple/apple-touch-icon-180x180.png';
const DEFAULT_NOTIFICATION_BADGE = '/public/res/apple-touch-icon-72x72.png';
From 54d2ddf1f5e1429a41ca23fd620c009269d6e9b0 Mon Sep 17 00:00:00 2001
From: Kris Hu
Date: Mon, 28 Jul 2025 15:43:56 +0800
Subject: [PATCH 75/83] keep push notification alive
currenttly all browser requrire a `push` produces a notification, if
not, push subscription may be revoked.
see:
https://github.com/firebase/firebase-js-sdk/issues/8010#issuecomment-2119275829
in this case, sygnal, the push gateway will send unread count, and
create a `push` event, when messages are read on other clients.
Therefore we have no choice but to stop sygnal from pushing data that
won't be presented as notifications
see:
https://github.com/element-hq/sygnal/blob/da48ba7457409391c1d12140ce2ea3d49d377ff3/sygnal/webpushpushkin.py#L142-L145
---
.../notifications/PushNotifications.tsx | 1 +
src/app/pages/client/ClientNonUIFeatures.tsx | 11 +++++-
src/app/state/serviceWorkerRegistration.ts | 3 ++
src/sw.ts | 34 +++++++++----------
4 files changed, 31 insertions(+), 18 deletions(-)
create mode 100644 src/app/state/serviceWorkerRegistration.ts
diff --git a/src/app/features/settings/notifications/PushNotifications.tsx b/src/app/features/settings/notifications/PushNotifications.tsx
index 8a872a440..a67667ca1 100644
--- a/src/app/features/settings/notifications/PushNotifications.tsx
+++ b/src/app/features/settings/notifications/PushNotifications.tsx
@@ -41,6 +41,7 @@ export async function enablePushNotifications(
data: {
url: clientConfig.pushNotificationDetails?.pushNotifyUrl,
// format: 'event_id_only' as const,
+ events_only: true,
endpoint: pushSubAtom.endpoint,
p256dh: pushSubAtom.keys!.p256dh!,
auth: pushSubAtom.keys!.auth!,
diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx
index f9261df60..9acb90b33 100644
--- a/src/app/pages/client/ClientNonUIFeatures.tsx
+++ b/src/app/pages/client/ClientNonUIFeatures.tsx
@@ -27,6 +27,7 @@ import { useSelectedRoom } from '../../hooks/router/useSelectedRoom';
import { useInboxNotificationsSelected } from '../../hooks/router/useInbox';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
import { useRoomNavigate } from '../../hooks/useRoomNavigate';
+import { registrationAtom } from '../../state/serviceWorkerRegistration';
function SystemEmojiFeature() {
const [twitterEmoji] = useSetting(settingsAtom, 'twitterEmoji');
@@ -54,6 +55,8 @@ function PageZoomFeature() {
function FaviconUpdater() {
const roomToUnread = useAtomValue(roomToUnreadAtom);
+ const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications');
+ const registration = useAtomValue(registrationAtom);
useEffect(() => {
let notification = false;
@@ -81,7 +84,13 @@ function FaviconUpdater() {
} catch (e) {
// Likely Firefox/Gecko-based and doesn't support badging API
}
- }, [roomToUnread]);
+ if (usePushNotifications && total === 0) {
+ registration.getNotifications()
+ .then((pushNotifications) => pushNotifications
+ .forEach((pushNotification) => pushNotification.close()));
+ navigator.clearAppBadge();
+ }
+ }, [roomToUnread, usePushNotifications, registration]);
return null;
}
diff --git a/src/app/state/serviceWorkerRegistration.ts b/src/app/state/serviceWorkerRegistration.ts
new file mode 100644
index 000000000..6e9f94bd8
--- /dev/null
+++ b/src/app/state/serviceWorkerRegistration.ts
@@ -0,0 +1,3 @@
+import { atom } from "jotai";
+
+export const registrationAtom = atom(async () => navigator.serviceWorker.ready);
diff --git a/src/sw.ts b/src/sw.ts
index e9716e3ed..2b6209e83 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -140,23 +140,23 @@ const onPushNotification = async (event: PushEvent) => {
const pushData = event.data.json();
console.log(pushData);
- try {
- if (typeof pushData?.unread === 'number') {
- self.navigator.setAppBadge(pushData.unread);
-
- if (pushData.unread == 0) {
- self.registration.getNotifications()
- .then((notifications) => notifications
- .forEach((notification) => notification.close()));
- await navigator.clearAppBadge();
- return;
- }
- } else {
- await navigator.clearAppBadge();
- }
- } catch (_) {
- // Likely Firefox/Gecko-based and doesn't support badging API
- }
+ // try {
+ // if (typeof pushData?.unread === 'number') {
+ // self.navigator.setAppBadge(pushData.unread);
+ //
+ // if (pushData.unread == 0) {
+ // self.registration.getNotifications()
+ // .then((notifications) => notifications
+ // .forEach((notification) => notification.close()));
+ // await navigator.clearAppBadge();
+ // return;
+ // }
+ // } else {
+ // await navigator.clearAppBadge();
+ // }
+ // } catch (_) {
+ // // Likely Firefox/Gecko-based and doesn't support badging API
+ // }
await handlePushNotificationPushData(pushData);
};
From 6a9fe21fe98a17f86b16e6f9d022d71bec117089 Mon Sep 17 00:00:00 2001
From: Kris Hu
Date: Fri, 8 Aug 2025 10:21:42 +0800
Subject: [PATCH 76/83] fix(push): prevent sliding back after clicking push
notification killing the pwa
---
src/app/pages/Router.tsx | 2 +-
src/app/pages/client/ToRoomEvent.tsx | 3 ++-
2 files changed, 3 insertions(+), 2 deletions(-)
diff --git a/src/app/pages/Router.tsx b/src/app/pages/Router.tsx
index 74a3dc8b4..ab44c3b27 100644
--- a/src/app/pages/Router.tsx
+++ b/src/app/pages/Router.tsx
@@ -291,7 +291,7 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize)
} />
} />
- } />
+ } />
Page not found} />
diff --git a/src/app/pages/client/ToRoomEvent.tsx b/src/app/pages/client/ToRoomEvent.tsx
index ebe1bef93..a358ab1eb 100644
--- a/src/app/pages/client/ToRoomEvent.tsx
+++ b/src/app/pages/client/ToRoomEvent.tsx
@@ -1,8 +1,8 @@
import React, { useEffect } from "react";
import { useParams } from "react-router-dom";
+import { useAtomValue } from "jotai";
import { useRoomNavigate } from "../../hooks/useRoomNavigate";
import { useMatrixClient } from "../../hooks/useMatrixClient";
-import { useAtomValue } from "jotai";
import { roomToParentsAtom } from "../../state/room/roomToParents";
import { mDirectAtom } from "../../state/mDirectList";
@@ -17,6 +17,7 @@ export function ToRoomEvent() {
if (!room_id || !mx) { return; }
if (!roomToParents.size || !mDirects.size) { return; }
+ if (window.history.length <= 2) { window.history.pushState({}, "", "/"); }
navigateRoom(room_id, event_id);
}, [
mx,
From b56e793a15d1228bb2d08535fd74a9d58ad9de40 Mon Sep 17 00:00:00 2001
From: Kris Hu
Date: Mon, 18 Aug 2025 20:50:39 +0800
Subject: [PATCH 77/83] fix(noti): try-catch all badge API calls
---
src/app/pages/client/ClientNonUIFeatures.tsx | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx
index 9acb90b33..9f3a941d3 100644
--- a/src/app/pages/client/ClientNonUIFeatures.tsx
+++ b/src/app/pages/client/ClientNonUIFeatures.tsx
@@ -81,15 +81,15 @@ function FaviconUpdater() {
}
try {
navigator.setAppBadge(total);
+ if (usePushNotifications && total === 0) {
+ registration.getNotifications()
+ .then((pushNotifications) => pushNotifications
+ .forEach((pushNotification) => pushNotification.close()));
+ navigator.clearAppBadge();
+ }
} catch (e) {
// Likely Firefox/Gecko-based and doesn't support badging API
}
- if (usePushNotifications && total === 0) {
- registration.getNotifications()
- .then((pushNotifications) => pushNotifications
- .forEach((pushNotification) => pushNotification.close()));
- navigator.clearAppBadge();
- }
}, [roomToUnread, usePushNotifications, registration]);
return null;
From 3ee49852cb1e7897f589becefa99f5c88b992ee3 Mon Sep 17 00:00:00 2001
From: Kris Hu
Date: Thu, 28 Aug 2025 09:44:26 +0800
Subject: [PATCH 78/83] wait for sync for to room event navigation
---
src/app/pages/client/ToRoomEvent.tsx | 32 +++++++++++++++++++++++-----
1 file changed, 27 insertions(+), 5 deletions(-)
diff --git a/src/app/pages/client/ToRoomEvent.tsx b/src/app/pages/client/ToRoomEvent.tsx
index a358ab1eb..f81daa9d5 100644
--- a/src/app/pages/client/ToRoomEvent.tsx
+++ b/src/app/pages/client/ToRoomEvent.tsx
@@ -1,8 +1,12 @@
-import React, { useEffect } from "react";
+/* eslint-disable camelcase */
+import { useEffect, useState, useCallback } from "react";
import { useParams } from "react-router-dom";
import { useAtomValue } from "jotai";
+import { SyncState } from "matrix-js-sdk";
+
import { useRoomNavigate } from "../../hooks/useRoomNavigate";
import { useMatrixClient } from "../../hooks/useMatrixClient";
+import { useSyncState } from "../../hooks/useSyncState";
import { roomToParentsAtom } from "../../state/room/roomToParents";
import { mDirectAtom } from "../../state/mDirectList";
@@ -12,20 +16,38 @@ export function ToRoomEvent() {
const mDirects = useAtomValue(mDirectAtom);
const { room_id, event_id } = useParams();
const { navigateRoom } = useRoomNavigate();
+ const [syncState, setSyncState] = useState(
+ mx?.getSyncState() ?? null
+ );
+
+ useSyncState(
+ mx,
+ useCallback((s) => setSyncState(s), [])
+ );
useEffect(() => {
- if (!room_id || !mx) { return; }
- if (!roomToParents.size || !mDirects.size) { return; }
+ if (!room_id || !mx) {
+ return;
+ }
+ if (syncState !== SyncState.Syncing) {
+ return;
+ }
+ if (!roomToParents.size || !mDirects.size) {
+ return;
+ }
- if (window.history.length <= 2) { window.history.pushState({}, "", "/"); }
+ if (window.history.length <= 2) {
+ window.history.pushState({}, "", "/");
+ }
navigateRoom(room_id, event_id);
}, [
mx,
+ syncState,
roomToParents,
mDirects,
room_id,
event_id,
- navigateRoom
+ navigateRoom,
]);
return null;
From f66545bbd8c7bcfce868591b9d6e1bec9d60ee71 Mon Sep 17 00:00:00 2001
From: Kris Hu
Date: Thu, 28 Aug 2025 20:05:50 +0800
Subject: [PATCH 79/83] add a fallback push notification
so that a notification will always be generated from a push event,
avoiding being killed for privacy policies from browser and os
---
src/sw.ts | 4 +++-
src/sw/pushNotification.ts | 26 +++++++++++++++++---------
2 files changed, 20 insertions(+), 10 deletions(-)
diff --git a/src/sw.ts b/src/sw.ts
index 2b6209e83..2dfb7e2cc 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -1,7 +1,7 @@
///
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
-import { usePushNotifications } from './sw/pushNotification';
import { EventType } from "matrix-js-sdk/lib/@types/event";
+import { usePushNotifications } from './sw/pushNotification';
export type {};
declare const self: ServiceWorkerGlobalScope;
@@ -204,6 +204,8 @@ self.addEventListener('notificationclick', (event: NotificationEvent) => {
return Promise.resolve();
})
);
+
+ return Promise.resolve();
});
if (self.__WB_MANIFEST) {
diff --git a/src/sw/pushNotification.ts b/src/sw/pushNotification.ts
index 8e5073bca..140f31775 100644
--- a/src/sw/pushNotification.ts
+++ b/src/sw/pushNotification.ts
@@ -1,3 +1,4 @@
+/* eslint-disable camelcase */
import { EventType } from "matrix-js-sdk/lib/@types/event";
const DEFAULT_NOTIFICATION_ICON = '/public/res/apple/apple-touch-icon-180x180.png';
@@ -79,28 +80,35 @@ export const usePushNotifications = (self: ServiceWorkerGlobalScope) => {
)
};
+ const fallbackNotification = async () => {
+ await self.registration.showNotification("You have a new notification", {
+ icon: DEFAULT_NOTIFICATION_ICON,
+ badge: DEFAULT_NOTIFICATION_BADGE,
+ tag: "Cinny",
+ });
+ };
+
const handlePushNotificationPushData = async (pushData: any) => {
const eventType = pushData?.type as (EventType | undefined);
if (!eventType) {
- console.log("no event type");
- return;
+ console.warn("no event type");
}
switch (eventType) {
case EventType.RoomMessage:
- await handleRoomMessageNotification(pushData);
- return;
+ return handleRoomMessageNotification(pushData);
case EventType.RoomMessageEncrypted:
- await handleEncryptedMessageNotification(pushData);
- return;
+ return handleEncryptedMessageNotification(pushData);
case EventType.RoomMember:
- if (!(pushData?.content?.membership == "invite")) return;
- await handleInvitationNotification(pushData);
- return;
+ if (!(pushData?.content?.membership === "invite")) break;
+ return handleInvitationNotification(pushData);
+
default:
// no voip support in app anyway
return;
}
+
+ return fallbackNotification();
};
return { handlePushNotificationPushData };
From ad723f6b20ac5a5e7a3c2cebf937cf7f9aa3920f Mon Sep 17 00:00:00 2001
From: Kris Hu
Date: Sat, 30 Aug 2025 11:33:21 +0800
Subject: [PATCH 80/83] lint code
---
src/app/pages/client/ClientNonUIFeatures.tsx | 59 ++++++++++----------
src/sw.ts | 14 ++---
src/sw/pushNotification.ts | 2 +-
3 files changed, 37 insertions(+), 38 deletions(-)
diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx
index 9f3a941d3..67b984c65 100644
--- a/src/app/pages/client/ClientNonUIFeatures.tsx
+++ b/src/app/pages/client/ClientNonUIFeatures.tsx
@@ -1,7 +1,7 @@
import { useAtomValue } from 'jotai';
import React, { ReactNode, useCallback, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
-import { RoomEvent, RoomEventHandlerMap } from 'matrix-js-sdk';
+import { EventType, RoomEvent, RoomEventHandlerMap } from 'matrix-js-sdk';
import { roomToUnreadAtom, unreadEqual, unreadInfoToUnread } from '../../state/room/roomToUnread';
import LogoSVG from '../../../../public/res/svg/cinny.svg';
import LogoUnreadSVG from '../../../../public/res/svg/cinny-unread.svg';
@@ -129,7 +129,7 @@ function InviteNotifications() {
}, []);
useEffect(() => {
- if (usePushNotifications && document.visibilityState != "visible") return;
+ if (usePushNotifications && document.visibilityState !== "visible") return;
if (invites.length > perviousInviteLen && mx.getSyncState() === 'SYNCING') {
if (showNotifications && notificationPermission('granted')) {
notify(invites.length - perviousInviteLen);
@@ -217,7 +217,7 @@ function MessageNotifications() {
data
) => {
if (mx.getSyncState() !== 'SYNCING') return;
- if (usePushNotifications && document.visibilityState != "visible") return;
+ if (usePushNotifications && document.visibilityState !== "visible") return;
if (document.hasFocus() && (selectedRoomId === room?.roomId || notificationSelected)) return;
if (
@@ -291,38 +291,37 @@ function HandleNotificationClick() {
const { navigateRoom } = useRoomNavigate();
const navigate = useNavigate();
- const handleNotificationClickEvent = (event: any) => {
- if (
- !event.data ||
- !event.source
- ) return;
- const eventData = event.data;
- if (!(eventData?.type == "notificationToRoomEvent")) return;
- const messageData = eventData?.message;
- if (!messageData) navigate(getInboxNotificationsPath());
-
- const eventType = messageData!.type as EventType;
- switch (eventType) {
- case EventType.RoomMessage:
- case EventType.RoomMessageEncrypted:
- navigateRoom(messageData!.room_id, messageData!.event_id);
- return;
- case EventType.RoomMember:
- if (!(messageData?.content?.membership == "invite")) return;
- navigate(getInboxInvitesPath());
- return;
- default:
- return;
- }
- };
-
useEffect(() => {
+ const handleNotificationClickEvent = (event: any) => {
+ if (
+ !event.data ||
+ !event.source
+ ) return;
+ const eventData = event.data;
+ if (!(eventData?.type === "notificationToRoomEvent")) return;
+ const messageData = eventData?.message;
+ if (!messageData) navigate(getInboxNotificationsPath());
+
+ const eventType = messageData!.type as EventType;
+ switch (eventType) {
+ case EventType.RoomMessage:
+ case EventType.RoomMessageEncrypted:
+ navigateRoom(messageData!.room_id, messageData!.event_id);
+ return;
+ case EventType.RoomMember:
+ if (!(messageData?.content?.membership === "invite")) return;
+ navigate(getInboxInvitesPath());
+ break;
+ default:
+ break;
+ }
+ };
+
navigator.serviceWorker.addEventListener("message", handleNotificationClickEvent);
- console.log("notification click event is listening on main thread");
return () => {
navigator.serviceWorker.removeEventListener("message", handleNotificationClickEvent);
}
- }, [navigateRoom]);
+ }, [navigate, navigateRoom]);
return null;
}
diff --git a/src/sw.ts b/src/sw.ts
index 2dfb7e2cc..01d0cc235 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -3,7 +3,7 @@ import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
import { EventType } from "matrix-js-sdk/lib/@types/event";
import { usePushNotifications } from './sw/pushNotification';
-export type {};
+export type { };
declare const self: ServiceWorkerGlobalScope;
const { handlePushNotificationPushData } = usePushNotifications(self);
@@ -126,7 +126,7 @@ self.addEventListener('fetch', (event: FetchEvent) => {
})()
);
event.waitUntil(
- (async function () {
+ (async function() {
console.log('Ensuring fetch processing completes before worker termination.');
})()
);
@@ -167,20 +167,20 @@ self.addEventListener('notificationclick', (event: NotificationEvent) => {
event.notification.close();
const messageData = event.notification.data;
- const scope = self.registration.scope;
+ const { scope } = self.registration;
console.log(messageData);
const eventType = messageData?.type as (EventType | undefined);
if (!eventType) return Promise.resolve();
- let targetUrl: string = `${scope}inbox/`;
+ let targetUrl = `${scope}inbox/`;
if (
- (eventType == EventType.RoomMessage || eventType == EventType.RoomMessageEncrypted) &&
+ (eventType === EventType.RoomMessage || eventType === EventType.RoomMessageEncrypted) &&
messageData?.room_id && messageData?.event_id
) targetUrl = `${scope}to/${messageData.room_id}/${messageData.event_id}`;
if (
- eventType == EventType.RoomMember &&
- messageData?.content?.membership == "invite"
+ eventType === EventType.RoomMember &&
+ messageData?.content?.membership === "invite"
) targetUrl = `${scope}inbox/invites/`;
console.log(`target url = ${targetUrl}`);
diff --git a/src/sw/pushNotification.ts b/src/sw/pushNotification.ts
index 140f31775..bded7f591 100644
--- a/src/sw/pushNotification.ts
+++ b/src/sw/pushNotification.ts
@@ -56,7 +56,7 @@ export const usePushNotifications = (self: ServiceWorkerGlobalScope) => {
const sender_display_name = pushData?.sender_display_name;
const room_name = pushData?.room_name;
- let body: string = "";
+ let body = "";
if (sender_display_name && room_name)
body = `${sender_display_name} invites you to ${room_name}`;
if (sender_display_name && !room_name)
From 3d792f34f9daf9143521e2aa060fd8cd5430ecaa Mon Sep 17 00:00:00 2001
From: Kris Hu
Date: Thu, 23 Oct 2025 09:47:03 +0800
Subject: [PATCH 81/83] lint: minor error during merging
---
src/sw/pushNotification.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/sw/pushNotification.ts b/src/sw/pushNotification.ts
index bded7f591..25e8009b4 100644
--- a/src/sw/pushNotification.ts
+++ b/src/sw/pushNotification.ts
@@ -105,7 +105,7 @@ export const usePushNotifications = (self: ServiceWorkerGlobalScope) => {
default:
// no voip support in app anyway
- return;
+ break;
}
return fallbackNotification();
From 09bd903398db8bc105ee122c048d23ed49fff741 Mon Sep 17 00:00:00 2001
From: Kris Hu
Date: Fri, 5 Sep 2025 08:26:58 +0800
Subject: [PATCH 82/83] add `m.sticker` support in push notification
---
src/sw/pushNotification.ts | 29 +++++++++++++++++++++--------
1 file changed, 21 insertions(+), 8 deletions(-)
diff --git a/src/sw/pushNotification.ts b/src/sw/pushNotification.ts
index 25e8009b4..5337846a5 100644
--- a/src/sw/pushNotification.ts
+++ b/src/sw/pushNotification.ts
@@ -8,7 +8,7 @@ export const usePushNotifications = (self: ServiceWorkerGlobalScope) => {
const showNotificationWithData = async (
title: string,
- body: string,
+ body: string | undefined,
data: any,
silent: boolean | null = null
) => {
@@ -80,12 +80,24 @@ export const usePushNotifications = (self: ServiceWorkerGlobalScope) => {
)
};
- const fallbackNotification = async () => {
- await self.registration.showNotification("You have a new notification", {
- icon: DEFAULT_NOTIFICATION_ICON,
- badge: DEFAULT_NOTIFICATION_BADGE,
- tag: "Cinny",
- });
+ const fallbackNotification = async (pushData: any) => {
+ const body = pushData?.content?.body;
+ let title;
+ if (body) {
+ title = pushData?.sender_display_name
+ ? `${pushData.sender_display_name}${pushData?.room_name ? ` in ${pushData.room_name}` : ''}`
+ : "New Notification";
+ } else {
+ title = "You have a new Notification";
+ }
+ const data = {
+ type: pushData?.type,
+ room_id: pushData?.room_id,
+ event_id: pushData?.event_id,
+ timestamp: Date.now(),
+ ...pushData.data
+ };
+ await showNotificationWithData(title, body, data, pushData.silent ?? false);
};
const handlePushNotificationPushData = async (pushData: any) => {
@@ -96,6 +108,7 @@ export const usePushNotifications = (self: ServiceWorkerGlobalScope) => {
switch (eventType) {
case EventType.RoomMessage:
+ case EventType.Sticker:
return handleRoomMessageNotification(pushData);
case EventType.RoomMessageEncrypted:
return handleEncryptedMessageNotification(pushData);
@@ -108,7 +121,7 @@ export const usePushNotifications = (self: ServiceWorkerGlobalScope) => {
break;
}
- return fallbackNotification();
+ return fallbackNotification(pushData);
};
return { handlePushNotificationPushData };
From 37c76c78b15aad0018cf36106afca96df64f122c Mon Sep 17 00:00:00 2001
From: Max <165057920+OE1KHZ@users.noreply.github.com>
Date: Sat, 29 Nov 2025 01:17:46 +0100
Subject: [PATCH 83/83] fix misleading email format (#32)
Sygnal already adds `mailto:` by itself. When added manually, apple will error out with `403: BadJwtToken`. Hence the mailto should be removed :)
(cherry picked from commit 0d6676233c965b3a1857015bbb59b7c1dbd0868e)
Signed-off-by: Kris Hu
---
docs/sygnal-setup.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/sygnal-setup.md b/docs/sygnal-setup.md
index 0a13fa43e..0619433fd 100644
--- a/docs/sygnal-setup.md
+++ b/docs/sygnal-setup.md
@@ -128,7 +128,7 @@ apps:
# This path is *inside the container*. We will map our generated key to it.
vapid_private_key: /data/private_key.pem
# An email for VAPID contact details
- vapid_contact_email: mailto:your-email@your-domain.com
+ vapid_contact_email: your-email@your-domain.com
```
#### 3.3. Caddy Configuration (`Caddyfile`)