feat(web): add WhatsApp Web-style background push notifications, onboarding banner, and deep-linking

This commit is contained in:
tyuXX 2026-10-31 16:10:32 +03:00
parent 7cc9ba7f4d
commit dcccc67d3e
8 changed files with 248 additions and 34 deletions

View file

@ -182,6 +182,7 @@ public class WebPushService : IDisposable
using var request = new HttpRequestMessage(HttpMethod.Post, sub.Endpoint); using var request = new HttpRequestMessage(HttpMethod.Post, sub.Endpoint);
request.Headers.TryAddWithoutValidation("Authorization", vapidHeader); request.Headers.TryAddWithoutValidation("Authorization", vapidHeader);
request.Headers.TryAddWithoutValidation("Crypto-Key", $"p256ecdsa={_options.VapidPublicKey}");
request.Headers.TryAddWithoutValidation("TTL", "86400"); request.Headers.TryAddWithoutValidation("TTL", "86400");
request.Headers.TryAddWithoutValidation("Urgency", "high"); request.Headers.TryAddWithoutValidation("Urgency", "high");

View file

@ -228,6 +228,72 @@ html, body {
text-transform: uppercase; text-transform: uppercase;
} }
/* ==========================================================================
WhatsApp Web Style Desktop Notification Banner
========================================================================== */
.notif-banner {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 8px 16px;
background-color: var(--ctp-mantle);
border-bottom: 1px solid var(--ctp-mauve);
color: var(--ctp-text);
font-family: var(--font-mono);
font-size: 0.84rem;
flex-shrink: 0;
}
.notif-banner-icon {
font-size: 1.2rem;
color: var(--ctp-mauve);
line-height: 1;
}
.notif-banner-body {
display: flex;
flex-direction: column;
flex: 1;
min-width: 0;
gap: 2px;
}
.notif-banner-title {
font-weight: 700;
color: var(--ctp-mauve);
font-size: 0.86rem;
}
.notif-banner-desc {
font-size: 0.76rem;
color: var(--ctp-subtext0);
}
.notif-banner-actions {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.notif-banner-dismiss {
background: transparent;
border: 1px solid transparent;
color: var(--ctp-overlay0);
font-family: var(--font-mono);
font-size: 1rem;
cursor: pointer;
padding: 2px 6px;
transition: color 0.1s, border-color 0.1s;
}
.notif-banner-dismiss:hover {
color: var(--ctp-red);
border-color: var(--ctp-red);
}
/* ========================================================================== /* ==========================================================================
Main Content Views Main Content Views
========================================================================== */ ========================================================================== */

View file

@ -50,6 +50,10 @@
tabViews: document.querySelectorAll('.tab-view'), tabViews: document.querySelectorAll('.tab-view'),
currentUsername: document.getElementById('currentUsername'), currentUsername: document.getElementById('currentUsername'),
currentUserRole: document.getElementById('currentUserRole'), currentUserRole: document.getElementById('currentUserRole'),
headerPushBtn: document.getElementById('headerPushBtn'),
desktopNotifBanner: document.getElementById('desktopNotifBanner'),
bannerEnablePushBtn: document.getElementById('bannerEnablePushBtn'),
bannerDismissBtn: document.getElementById('bannerDismissBtn'),
e2eeVaultBtn: document.getElementById('e2eeVaultBtn'), e2eeVaultBtn: document.getElementById('e2eeVaultBtn'),
logoutBtn: document.getElementById('logoutBtn'), logoutBtn: document.getElementById('logoutBtn'),
userBadge: document.getElementById('userBadge'), userBadge: document.getElementById('userBadge'),
@ -644,7 +648,10 @@
} }
async function initServiceWorkerAndPush() { async function initServiceWorkerAndPush() {
if (!('serviceWorker' in navigator)) return; if (!('serviceWorker' in navigator)) {
updateDesktopNotifBanner();
return;
}
try { try {
const reg = await navigator.serviceWorker.register('/sw.js'); const reg = await navigator.serviceWorker.register('/sw.js');
state.swRegistration = reg; state.swRegistration = reg;
@ -667,13 +674,64 @@
if (reg.pushManager) { if (reg.pushManager) {
const existingSub = await reg.pushManager.getSubscription(); const existingSub = await reg.pushManager.getSubscription();
state.pushSubscribed = !!existingSub; state.pushSubscribed = !!existingSub;
updateInboxPreferencesUI();
if (existingSub && state.token) { if (existingSub && state.token) {
await syncSubscriptionToServer(existingSub); await syncSubscriptionToServer(existingSub);
} else if (!existingSub && 'Notification' in window && Notification.permission === 'granted' && state.token) {
// If browser has already granted permission, auto-subscribe seamlessly like WhatsApp Web
await subscribeWebPush(false);
} }
} }
} catch (err) { } catch (err) {
console.warn('Service Worker registration skipped or failed:', err); console.warn('Service Worker registration skipped or failed:', err);
} finally {
updateDesktopNotifBanner();
updateInboxPreferencesUI();
}
}
function updateDesktopNotifBanner() {
initElements();
const hasPushApi = ('Notification' in window) && ('serviceWorker' in navigator);
if (el.headerPushBtn) {
if (!hasPushApi) {
el.headerPushBtn.style.display = 'none';
} else {
el.headerPushBtn.style.display = '';
if (Notification.permission === 'granted') {
if (state.pushSubscribed) {
el.headerPushBtn.textContent = '[🔔 Push: ON]';
el.headerPushBtn.className = 'btn btn-sm btn-primary';
el.headerPushBtn.title = 'Background Web Push is active (click to disable)';
} else {
el.headerPushBtn.textContent = '[🔔 Enable Push]';
el.headerPushBtn.className = 'btn btn-sm btn-outline-primary';
el.headerPushBtn.title = 'Click to activate background Web Push';
}
} else if (Notification.permission === 'denied') {
el.headerPushBtn.textContent = '[🔕 Push: Blocked]';
el.headerPushBtn.className = 'btn btn-sm btn-secondary';
el.headerPushBtn.title = 'Notifications are blocked in browser site permissions';
} else {
el.headerPushBtn.textContent = '[🔔 Enable Push]';
el.headerPushBtn.className = 'btn btn-sm btn-outline-primary';
el.headerPushBtn.title = 'Enable background Web Push notifications';
}
}
}
if (!el.desktopNotifBanner) return;
if (!hasPushApi || !state.token || Notification.permission === 'granted' || Notification.permission === 'denied') {
el.desktopNotifBanner.style.display = 'none';
return;
}
const dismissed = localStorage.getItem('gsdchat_dismiss_push_banner') === 'true';
if (dismissed) {
el.desktopNotifBanner.style.display = 'none';
} else {
el.desktopNotifBanner.style.display = 'flex';
} }
} }
@ -733,16 +791,17 @@
if (state.pushSubscribed) { if (state.pushSubscribed) {
await unsubscribeWebPush(); await unsubscribeWebPush();
} else { } else {
await subscribeWebPush(); await subscribeWebPush(true);
} }
} }
async function subscribeWebPush() { async function subscribeWebPush(interactive = true) {
try { try {
if ('Notification' in window) { if ('Notification' in window) {
const perm = await Notification.requestPermission(); const perm = await Notification.requestPermission();
if (perm !== 'granted') { if (perm !== 'granted') {
showToast('Notification permission denied by browser.'); if (interactive) showToast('Notification permission denied by browser.');
updateDesktopNotifBanner();
return; return;
} }
} }
@ -754,33 +813,40 @@
const vapidKey = await fetchVapidPublicKey(); const vapidKey = await fetchVapidPublicKey();
if (!vapidKey) { if (!vapidKey) {
showToast('Server VAPID public key is unavailable.'); if (interactive) showToast('Server VAPID public key is unavailable.');
return; return;
} }
const sub = await state.swRegistration.pushManager.subscribe({ let sub = await state.swRegistration.pushManager.getSubscription();
userVisibleOnly: true, if (!sub) {
applicationServerKey: urlBase64ToUint8Array(vapidKey) sub = await state.swRegistration.pushManager.subscribe({
}); userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(vapidKey)
});
}
const ok = await syncSubscriptionToServer(sub); const ok = await syncSubscriptionToServer(sub);
if (ok) { if (ok) {
state.pushSubscribed = true; state.pushSubscribed = true;
state.inboxPreferences.pushNotificationsEnabled = true; state.inboxPreferences.pushNotificationsEnabled = true;
sendEnvelope('UPDATE_INBOX_PREFERENCES', { if (state.socket && state.socket.readyState === WebSocket.OPEN) {
mentionsEnabled: state.inboxPreferences.mentionsEnabled, sendEnvelope('UPDATE_INBOX_PREFERENCES', {
announcementsEnabled: state.inboxPreferences.announcementsEnabled, mentionsEnabled: state.inboxPreferences.mentionsEnabled,
directMessagesEnabled: state.inboxPreferences.directMessagesEnabled, announcementsEnabled: state.inboxPreferences.announcementsEnabled,
followedChannelsEnabled: state.inboxPreferences.followedChannelsEnabled, directMessagesEnabled: state.inboxPreferences.directMessagesEnabled,
pushNotificationsEnabled: true followedChannelsEnabled: state.inboxPreferences.followedChannelsEnabled,
}); pushNotificationsEnabled: true
});
}
updateInboxPreferencesUI(); updateInboxPreferencesUI();
updateDesktopNotifBanner();
showToast('🔔 Background Web Push notifications enabled on this browser!'); showToast('🔔 Background Web Push notifications enabled on this browser!');
} else { } else {
showToast('Failed to register Web Push subscription with server.'); if (interactive) showToast('Failed to register Web Push subscription with server.');
} }
} catch (err) { } catch (err) {
showToast(`Web Push setup failed: ${err.message || err}`); if (interactive) showToast(`Web Push setup failed: ${err.message || err}`);
updateDesktopNotifBanner();
} }
} }
@ -807,6 +873,7 @@
} }
state.pushSubscribed = false; state.pushSubscribed = false;
updateInboxPreferencesUI(); updateInboxPreferencesUI();
updateDesktopNotifBanner();
showToast('🔕 Web Push notifications disabled on this browser.'); showToast('🔕 Web Push notifications disabled on this browser.');
} catch (err) { } catch (err) {
showToast(`Unsubscribe error: ${err.message || err}`); showToast(`Unsubscribe error: ${err.message || err}`);
@ -1004,6 +1071,8 @@
updateSettingsBadges(); updateSettingsBadges();
hideAuthModal(); hideAuthModal();
connectWebSocket(); connectWebSocket();
initServiceWorkerAndPush();
updateDesktopNotifBanner();
} catch (err) { } catch (err) {
el.authError.textContent = 'Connection error. Please try again.'; el.authError.textContent = 'Connection error. Please try again.';
} finally { } finally {
@ -1146,7 +1215,8 @@
sendInboxAction('mark_read', deepInboxItem); sendInboxAction('mark_read', deepInboxItem);
} }
if (deepChannel && getConversationById(deepChannel)) { if (deepChannel && getConversationById(deepChannel)) {
state.activeChannelId = deepChannel; joinChannel(deepChannel);
switchTab('chat');
window.history.replaceState({}, document.title, window.location.pathname); window.history.replaceState({}, document.title, window.location.pathname);
} }
} catch { } catch {
@ -1426,6 +1496,7 @@
el.toggleWebPushBtn.textContent = activePush ? '[🔔 Web Push: ON]' : '[🔕 Enable Web Push]'; el.toggleWebPushBtn.textContent = activePush ? '[🔔 Web Push: ON]' : '[🔕 Enable Web Push]';
el.toggleWebPushBtn.className = activePush ? 'btn btn-sm btn-primary' : 'btn btn-sm btn-secondary'; el.toggleWebPushBtn.className = activePush ? 'btn btn-sm btn-primary' : 'btn btn-sm btn-secondary';
} }
updateDesktopNotifBanner();
} }
function renderInbox() { function renderInbox() {
@ -2609,6 +2680,7 @@
if (state.socket) state.socket.close(); if (state.socket) state.socket.close();
hideE2eeModal(); hideE2eeModal();
updateUserUI(); updateUserUI();
updateDesktopNotifBanner();
showAuthModal(); showAuthModal();
} }
@ -2690,6 +2762,18 @@
if (el.toggleWebPushBtn) { if (el.toggleWebPushBtn) {
el.toggleWebPushBtn.addEventListener('click', toggleWebPushSubscription); el.toggleWebPushBtn.addEventListener('click', toggleWebPushSubscription);
} }
if (el.headerPushBtn) {
el.headerPushBtn.addEventListener('click', toggleWebPushSubscription);
}
if (el.bannerEnablePushBtn) {
el.bannerEnablePushBtn.addEventListener('click', () => subscribeWebPush(false));
}
if (el.bannerDismissBtn) {
el.bannerDismissBtn.addEventListener('click', () => {
localStorage.setItem('gsdchat_dismiss_push_banner', 'true');
if (el.desktopNotifBanner) el.desktopNotifBanner.style.display = 'none';
});
}
if (el.testWebPushBtn) { if (el.testWebPushBtn) {
el.testWebPushBtn.addEventListener('click', sendTestWebPush); el.testWebPushBtn.addEventListener('click', sendTestWebPush);
} }

View file

@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 192" width="192" height="192">
<title>GsDChat</title>
<rect width="192" height="192" fill="#11111b" rx="28"/>
<rect x="8" y="8" width="176" height="176" fill="#181825" stroke="#cba6f7" stroke-width="4" rx="20"/>
<!-- Terminal Prompt >_ -->
<path d="M48 64 L84 96 L48 128" fill="none" stroke="#a6e3a1" stroke-width="14" stroke-linecap="round" stroke-linejoin="round"/>
<line x1="102" y1="128" x2="148" y2="128" stroke="#89b4fa" stroke-width="14" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 546 B

View file

@ -6,6 +6,7 @@
<meta name="theme-color" content="#11111b"> <meta name="theme-color" content="#11111b">
<meta name="color-scheme" content="dark"> <meta name="color-scheme" content="dark">
<title>GsDChat - Web Client</title> <title>GsDChat - Web Client</title>
<link rel="icon" type="image/svg+xml" href="/icon.svg">
<link rel="manifest" href="/manifest.json"> <link rel="manifest" href="/manifest.json">
<!-- Preload stylesheet to prevent flash of unstyled content and forced layout reflow --> <!-- Preload stylesheet to prevent flash of unstyled content and forced layout reflow -->
<link rel="preload" href="/app.css" as="style"> <link rel="preload" href="/app.css" as="style">
@ -58,11 +59,25 @@
<span class="user-name" id="currentUsername"></span> <span class="user-name" id="currentUsername"></span>
<span class="user-role" id="currentUserRole"></span> <span class="user-role" id="currentUserRole"></span>
</div> </div>
<button class="btn btn-secondary btn-sm" id="headerPushBtn" title="Toggle background Web Push notifications" style="display:none;">[🔔 Push: OFF]</button>
<button class="btn btn-secondary btn-sm" id="e2eeVaultBtn" title="Manage E2EE PIN Vault &amp; Encryption Settings" style="display:none;">[🔒 E2EE Vault]</button> <button class="btn btn-secondary btn-sm" id="e2eeVaultBtn" title="Manage E2EE PIN Vault &amp; Encryption Settings" style="display:none;">[🔒 E2EE Vault]</button>
<button class="btn btn-outline-danger btn-sm" id="logoutBtn" title="Logout">[Disconnect]</button> <button class="btn btn-outline-danger btn-sm" id="logoutBtn" title="Logout">[Disconnect]</button>
</div> </div>
</header> </header>
<!-- WhatsApp Web Style Desktop Notifications Opt-in Banner -->
<div id="desktopNotifBanner" class="notif-banner" style="display:none;">
<div class="notif-banner-icon">🔔</div>
<div class="notif-banner-body">
<span class="notif-banner-title">Get notified of new messages</span>
<span class="notif-banner-desc">Turn on desktop notifications to receive alerts even when GsDChat is closed.</span>
</div>
<div class="notif-banner-actions">
<button type="button" class="btn btn-sm btn-primary" id="bannerEnablePushBtn">[ Turn on desktop notifications &gt; ]</button>
<button type="button" class="notif-banner-dismiss" id="bannerDismissBtn" title="Dismiss">✕</button>
</div>
</div>
<!-- Main Views Container --> <!-- Main Views Container -->
<main class="app-main"> <main class="app-main">

View file

@ -4,7 +4,14 @@
"description": "High-performance terminal-inspired hybrid chat with End-to-End Encryption, Inbox, and Web Push Notifications.", "description": "High-performance terminal-inspired hybrid chat with End-to-End Encryption, Inbox, and Web Push Notifications.",
"start_url": "/", "start_url": "/",
"display": "standalone", "display": "standalone",
"background_color": "#0d1117", "background_color": "#11111b",
"theme_color": "#00d4ff", "theme_color": "#cba6f7",
"icons": [] "icons": [
{
"src": "/icon.svg",
"sizes": "192x192 512x512",
"type": "image/svg+xml",
"purpose": "any maskable"
}
]
} }

View file

@ -1,5 +1,6 @@
// ============================================================================ // ============================================================================
// GsDChat Service Worker (Web Push Notifications & Background Deep-Linking) // GsDChat Service Worker (Web Push Notifications & Background Deep-Linking)
// Functions like WhatsApp Web: delivers notifications even when app is closed.
// ============================================================================ // ============================================================================
self.addEventListener('install', (event) => { self.addEventListener('install', (event) => {
@ -43,15 +44,15 @@ self.addEventListener('push', (event) => {
// Check if any open client window is currently focused in the foreground // Check if any open client window is currently focused in the foreground
let focusedClient = null; let focusedClient = null;
for (const client of windowClients) { for (const client of windowClients) {
if (client.focused || client.visibilityState === 'visible') { if (client.focused) {
focusedClient = client; focusedClient = client;
break; break;
} }
} }
if (focusedClient && focusedClient.focused) { if (focusedClient) {
// Suppress duplicate OS popup if the user is actively focused on the app; // Suppress duplicate OS popup if user is actively focused on the chat window;
// notify the foreground window so it can play an indicator if desired. // notify the foreground window so it can update badges/chime if desired.
focusedClient.postMessage({ focusedClient.postMessage({
type: 'PUSH_RECEIVED_FOREGROUND', type: 'PUSH_RECEIVED_FOREGROUND',
payload: payload payload: payload
@ -63,12 +64,20 @@ self.addEventListener('push', (event) => {
? `gsdchat-${payload.category || 'notif'}-${payload.channelId}` ? `gsdchat-${payload.category || 'notif'}-${payload.channelId}`
: `gsdchat-item-${payload.itemId || Date.now()}`; : `gsdchat-item-${payload.itemId || Date.now()}`;
await self.registration.showNotification(payload.title || 'GsDChat', { const notificationOptions = {
body: payload.body || 'New activity in GsDChat', body: payload.body || 'New message in GsDChat',
icon: '/icon.svg',
badge: '/icon.svg',
tag: tag, tag: tag,
renotify: true, renotify: true,
data: payload vibrate: [200, 100, 200],
}); data: payload,
actions: [
{ action: 'open', title: 'Open Chat' }
]
};
await self.registration.showNotification(payload.title || 'GsDChat', notificationOptions);
})()); })());
}); });
@ -76,6 +85,10 @@ self.addEventListener('notificationclick', (event) => {
event.notification.close(); event.notification.close();
const data = event.notification.data || {}; const data = event.notification.data || {};
const targetUrl = data.channelId
? `/?channel=${encodeURIComponent(data.channelId)}&inboxItem=${encodeURIComponent(data.itemId || '')}`
: '/';
event.waitUntil((async () => { event.waitUntil((async () => {
const windowClients = await self.clients.matchAll({ const windowClients = await self.clients.matchAll({
type: 'window', type: 'window',
@ -95,9 +108,6 @@ self.addEventListener('notificationclick', (event) => {
} }
if (self.clients.openWindow) { if (self.clients.openWindow) {
const targetUrl = data.channelId
? `/?channel=${encodeURIComponent(data.channelId)}&inboxItem=${encodeURIComponent(data.itemId || '')}`
: '/';
await self.clients.openWindow(targetUrl); await self.clients.openWindow(targetUrl);
} }
})()); })());

View file

@ -109,6 +109,10 @@ public class WebClientStaticTests : IAsyncLifetime
Assert.Contains("id=\"navTabInbox\"", html); Assert.Contains("id=\"navTabInbox\"", html);
Assert.Contains("id=\"inboxUnreadBadge\"", html); Assert.Contains("id=\"inboxUnreadBadge\"", html);
Assert.Contains("id=\"toggleWebPushBtn\"", html); Assert.Contains("id=\"toggleWebPushBtn\"", html);
Assert.Contains("id=\"desktopNotifBanner\"", html);
Assert.Contains("id=\"bannerEnablePushBtn\"", html);
Assert.Contains("id=\"headerPushBtn\"", html);
Assert.Contains("rel=\"icon\"", html);
} }
[Fact] [Fact]
@ -125,6 +129,7 @@ public class WebClientStaticTests : IAsyncLifetime
Assert.Contains(".conv-security-badge", css); Assert.Contains(".conv-security-badge", css);
Assert.Contains(".inbox-item", css); Assert.Contains(".inbox-item", css);
Assert.Contains(".inbox-badge", css); Assert.Contains(".inbox-badge", css);
Assert.Contains(".notif-banner", css);
} }
[Fact] [Fact]
@ -146,6 +151,8 @@ public class WebClientStaticTests : IAsyncLifetime
Assert.Contains("INBOX_SYNC", js); Assert.Contains("INBOX_SYNC", js);
Assert.Contains("INBOX_NEW_ITEM", js); Assert.Contains("INBOX_NEW_ITEM", js);
Assert.Contains("subscribeWebPush", js); Assert.Contains("subscribeWebPush", js);
Assert.Contains("updateDesktopNotifBanner", js);
Assert.Contains("initServiceWorkerAndPush", js);
} }
[Fact] [Fact]
@ -158,10 +165,26 @@ public class WebClientStaticTests : IAsyncLifetime
string swJs = await swRes.Content.ReadAsStringAsync(); string swJs = await swRes.Content.ReadAsStringAsync();
Assert.Contains("showNotification", swJs); Assert.Contains("showNotification", swJs);
Assert.Contains("notificationclick", swJs); Assert.Contains("notificationclick", swJs);
Assert.Contains("/icon.svg", swJs);
Assert.Contains("renotify: true", swJs);
var manifestRes = await _httpClient.GetAsync("/manifest.json"); var manifestRes = await _httpClient.GetAsync("/manifest.json");
Assert.True(manifestRes.IsSuccessStatusCode); Assert.True(manifestRes.IsSuccessStatusCode);
string manifestJson = await manifestRes.Content.ReadAsStringAsync(); string manifestJson = await manifestRes.Content.ReadAsStringAsync();
Assert.Contains("GsDChat", manifestJson); Assert.Contains("GsDChat", manifestJson);
Assert.Contains("icons", manifestJson);
Assert.Contains("/icon.svg", manifestJson);
}
[Fact]
public async Task GetIconSvg_ShouldServeValidSvg()
{
Assert.NotNull(_httpClient);
var iconRes = await _httpClient.GetAsync("/icon.svg");
Assert.True(iconRes.IsSuccessStatusCode);
string svg = await iconRes.Content.ReadAsStringAsync();
Assert.Contains("<svg", svg);
Assert.Contains("GsDChat", svg);
} }
} }