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);
request.Headers.TryAddWithoutValidation("Authorization", vapidHeader);
request.Headers.TryAddWithoutValidation("Crypto-Key", $"p256ecdsa={_options.VapidPublicKey}");
request.Headers.TryAddWithoutValidation("TTL", "86400");
request.Headers.TryAddWithoutValidation("Urgency", "high");

View file

@ -228,6 +228,72 @@ html, body {
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
========================================================================== */

View file

@ -50,6 +50,10 @@
tabViews: document.querySelectorAll('.tab-view'),
currentUsername: document.getElementById('currentUsername'),
currentUserRole: document.getElementById('currentUserRole'),
headerPushBtn: document.getElementById('headerPushBtn'),
desktopNotifBanner: document.getElementById('desktopNotifBanner'),
bannerEnablePushBtn: document.getElementById('bannerEnablePushBtn'),
bannerDismissBtn: document.getElementById('bannerDismissBtn'),
e2eeVaultBtn: document.getElementById('e2eeVaultBtn'),
logoutBtn: document.getElementById('logoutBtn'),
userBadge: document.getElementById('userBadge'),
@ -644,7 +648,10 @@
}
async function initServiceWorkerAndPush() {
if (!('serviceWorker' in navigator)) return;
if (!('serviceWorker' in navigator)) {
updateDesktopNotifBanner();
return;
}
try {
const reg = await navigator.serviceWorker.register('/sw.js');
state.swRegistration = reg;
@ -667,13 +674,64 @@
if (reg.pushManager) {
const existingSub = await reg.pushManager.getSubscription();
state.pushSubscribed = !!existingSub;
updateInboxPreferencesUI();
if (existingSub && state.token) {
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) {
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) {
await unsubscribeWebPush();
} else {
await subscribeWebPush();
await subscribeWebPush(true);
}
}
async function subscribeWebPush() {
async function subscribeWebPush(interactive = true) {
try {
if ('Notification' in window) {
const perm = await Notification.requestPermission();
if (perm !== 'granted') {
showToast('Notification permission denied by browser.');
if (interactive) showToast('Notification permission denied by browser.');
updateDesktopNotifBanner();
return;
}
}
@ -754,19 +813,23 @@
const vapidKey = await fetchVapidPublicKey();
if (!vapidKey) {
showToast('Server VAPID public key is unavailable.');
if (interactive) showToast('Server VAPID public key is unavailable.');
return;
}
const sub = await state.swRegistration.pushManager.subscribe({
let sub = await state.swRegistration.pushManager.getSubscription();
if (!sub) {
sub = await state.swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(vapidKey)
});
}
const ok = await syncSubscriptionToServer(sub);
if (ok) {
state.pushSubscribed = true;
state.inboxPreferences.pushNotificationsEnabled = true;
if (state.socket && state.socket.readyState === WebSocket.OPEN) {
sendEnvelope('UPDATE_INBOX_PREFERENCES', {
mentionsEnabled: state.inboxPreferences.mentionsEnabled,
announcementsEnabled: state.inboxPreferences.announcementsEnabled,
@ -774,13 +837,16 @@
followedChannelsEnabled: state.inboxPreferences.followedChannelsEnabled,
pushNotificationsEnabled: true
});
}
updateInboxPreferencesUI();
updateDesktopNotifBanner();
showToast('🔔 Background Web Push notifications enabled on this browser!');
} else {
showToast('Failed to register Web Push subscription with server.');
if (interactive) showToast('Failed to register Web Push subscription with server.');
}
} 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;
updateInboxPreferencesUI();
updateDesktopNotifBanner();
showToast('🔕 Web Push notifications disabled on this browser.');
} catch (err) {
showToast(`Unsubscribe error: ${err.message || err}`);
@ -1004,6 +1071,8 @@
updateSettingsBadges();
hideAuthModal();
connectWebSocket();
initServiceWorkerAndPush();
updateDesktopNotifBanner();
} catch (err) {
el.authError.textContent = 'Connection error. Please try again.';
} finally {
@ -1146,7 +1215,8 @@
sendInboxAction('mark_read', deepInboxItem);
}
if (deepChannel && getConversationById(deepChannel)) {
state.activeChannelId = deepChannel;
joinChannel(deepChannel);
switchTab('chat');
window.history.replaceState({}, document.title, window.location.pathname);
}
} catch {
@ -1426,6 +1496,7 @@
el.toggleWebPushBtn.textContent = activePush ? '[🔔 Web Push: ON]' : '[🔕 Enable Web Push]';
el.toggleWebPushBtn.className = activePush ? 'btn btn-sm btn-primary' : 'btn btn-sm btn-secondary';
}
updateDesktopNotifBanner();
}
function renderInbox() {
@ -2609,6 +2680,7 @@
if (state.socket) state.socket.close();
hideE2eeModal();
updateUserUI();
updateDesktopNotifBanner();
showAuthModal();
}
@ -2690,6 +2762,18 @@
if (el.toggleWebPushBtn) {
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) {
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="color-scheme" content="dark">
<title>GsDChat - Web Client</title>
<link rel="icon" type="image/svg+xml" href="/icon.svg">
<link rel="manifest" href="/manifest.json">
<!-- Preload stylesheet to prevent flash of unstyled content and forced layout reflow -->
<link rel="preload" href="/app.css" as="style">
@ -58,11 +59,25 @@
<span class="user-name" id="currentUsername"></span>
<span class="user-role" id="currentUserRole"></span>
</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-outline-danger btn-sm" id="logoutBtn" title="Logout">[Disconnect]</button>
</div>
</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 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.",
"start_url": "/",
"display": "standalone",
"background_color": "#0d1117",
"theme_color": "#00d4ff",
"icons": []
"background_color": "#11111b",
"theme_color": "#cba6f7",
"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)
// Functions like WhatsApp Web: delivers notifications even when app is closed.
// ============================================================================
self.addEventListener('install', (event) => {
@ -43,15 +44,15 @@ self.addEventListener('push', (event) => {
// Check if any open client window is currently focused in the foreground
let focusedClient = null;
for (const client of windowClients) {
if (client.focused || client.visibilityState === 'visible') {
if (client.focused) {
focusedClient = client;
break;
}
}
if (focusedClient && focusedClient.focused) {
// Suppress duplicate OS popup if the user is actively focused on the app;
// notify the foreground window so it can play an indicator if desired.
if (focusedClient) {
// Suppress duplicate OS popup if user is actively focused on the chat window;
// notify the foreground window so it can update badges/chime if desired.
focusedClient.postMessage({
type: 'PUSH_RECEIVED_FOREGROUND',
payload: payload
@ -63,12 +64,20 @@ self.addEventListener('push', (event) => {
? `gsdchat-${payload.category || 'notif'}-${payload.channelId}`
: `gsdchat-item-${payload.itemId || Date.now()}`;
await self.registration.showNotification(payload.title || 'GsDChat', {
body: payload.body || 'New activity in GsDChat',
const notificationOptions = {
body: payload.body || 'New message in GsDChat',
icon: '/icon.svg',
badge: '/icon.svg',
tag: tag,
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();
const data = event.notification.data || {};
const targetUrl = data.channelId
? `/?channel=${encodeURIComponent(data.channelId)}&inboxItem=${encodeURIComponent(data.itemId || '')}`
: '/';
event.waitUntil((async () => {
const windowClients = await self.clients.matchAll({
type: 'window',
@ -95,9 +108,6 @@ self.addEventListener('notificationclick', (event) => {
}
if (self.clients.openWindow) {
const targetUrl = data.channelId
? `/?channel=${encodeURIComponent(data.channelId)}&inboxItem=${encodeURIComponent(data.itemId || '')}`
: '/';
await self.clients.openWindow(targetUrl);
}
})());

View file

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