Explain notification setup failures and introduce notifications once per account
@@ -176,3 +176,7 @@ Notification clicks navigate to `./?game=ID`. The regular home screen loads; the
176
176
The manifest, 192/512-pixel maskable icons and Apple touch icon support installation within any deployment subdirectory. **Add to home screen** uses the browser's installation prompt when available, otherwise displays platform instructions. On iOS/iPadOS 16.4+, add to the home screen, open that installed app, sign in if needed, and enable notifications there. A closed tab can receive Web Push; delivery with the entire browser stopped depends on OS/browser background support and notification settings.
177
177
178
178
`php web/tests/push.php` verifies real VAPID authentication/encryption using an in-memory HTTP transport, expiration cleanup, recipient selection, stale-event suppression and subscription validation in an isolated database. API tests verify event triggers and authorization without contacting push services. Browser tests cover the notification link/highlight, reduced motion and service-worker activation. Actual background delivery and installation should also be checked on an Android device and an iPhone/iPad after deployment.
179
180
On first authenticated use, a one-time dialog explains where to enable turn notifications. Its atomic, CSRF-protected claim is stored per account in `notification_intro`, so simultaneous tabs and other devices do not repeat it. The dialog waits for other dialogs to close and never requests browser permission automatically. Existing accounts receive it once after this update as well.
181
182
Notification setup failures open a second dialog above Account. Push-service errors include the Brave settings address and setting name, framed as a possible cause, with alternative network advice. Other failures have permission/setup/save guidance. Closing the error leaves Account open and returns focus to its notification button.
@@ -176,3 +176,7 @@ Notification clicks navigate to `./?game=ID`. The regular home screen loads; the176
The manifest, 192/512-pixel maskable icons and Apple touch icon support installation within any deployment subdirectory. **Add to home screen** uses the browser's installation prompt when available, otherwise displays platform instructions. On iOS/iPadOS 16.4+, add to the home screen, open that installed app, sign in if needed, and enable notifications there. A closed tab can receive Web Push; delivery with the entire browser stopped depends on OS/browser background support and notification settings.176
The manifest, 192/512-pixel maskable icons and Apple touch icon support installation within any deployment subdirectory. **Add to home screen** uses the browser's installation prompt when available, otherwise displays platform instructions. On iOS/iPadOS 16.4+, add to the home screen, open that installed app, sign in if needed, and enable notifications there. A closed tab can receive Web Push; delivery with the entire browser stopped depends on OS/browser background support and notification settings.177
177
178
`php web/tests/push.php` verifies real VAPID authentication/encryption using an in-memory HTTP transport, expiration cleanup, recipient selection, stale-event suppression and subscription validation in an isolated database. API tests verify event triggers and authorization without contacting push services. Browser tests cover the notification link/highlight, reduced motion and service-worker activation. Actual background delivery and installation should also be checked on an Android device and an iPhone/iPad after deployment.178
`php web/tests/push.php` verifies real VAPID authentication/encryption using an in-memory HTTP transport, expiration cleanup, recipient selection, stale-event suppression and subscription validation in an isolated database. API tests verify event triggers and authorization without contacting push services. Browser tests cover the notification link/highlight, reduced motion and service-worker activation. Actual background delivery and installation should also be checked on an Android device and an iPhone/iPad after deployment.179
180
On first authenticated use, a one-time dialog explains where to enable turn notifications. Its atomic, CSRF-protected claim is stored per account in `notification_intro`, so simultaneous tabs and other devices do not repeat it. The dialog waits for other dialogs to close and never requests browser permission automatically. Existing accounts receive it once after this update as well.181
182
Notification setup failures open a second dialog above Account. Push-service errors include the Brave settings address and setting name, framed as a possible cause, with alternative network advice. Other failures have permission/setup/save guidance. Closing the error leaves Account open and returns focus to its notification button.@@ -76,7 +76,7 @@ try {
76
76
else $invite=['kind'=>$l['kind'],'name'=>$l['name'],'token'=>$l['token']];
77
77
}
78
78
$joined=query('SELECT joined FROM matchmaking WHERE user_id=?',[$u])->fetchColumn();
79
jsonOut(['user'=>profile($u),'csrf'=>$_SESSION['csrf'],'local'=>localDev(),'friends'=>$friends,'friendRequests'=>$requests,'games'=>array_map(fn($g)=>gameView($g,$u),$games),'invite'=>$invite,'matchmaking'=>$joined===false?null:['status'=>(int)$joined<=time()-86400?'expired':'searching']]);
79
jsonOut(['notificationIntroSeen'=>(bool)query('SELECT 1 FROM notification_intro WHERE user_id=?',[$u])->fetchColumn(),'user'=>profile($u),'csrf'=>$_SESSION['csrf'],'local'=>localDev(),'friends'=>$friends,'friendRequests'=>$requests,'games'=>array_map(fn($g)=>gameView($g,$u),$games),'invite'=>$invite,'matchmaking'=>$joined===false?null:['status'=>(int)$joined<=time()-86400?'expired':'searching']]);
80
80
}
81
81
if ($method!=='POST') fail('Method not allowed.',405);
82
82
if (!hash_equals($_SESSION['csrf']??'',$_SERVER['HTTP_X_CSRF_TOKEN']??'')) fail('Invalid session token. Reload the page.',403);
@@ -96,7 +96,9 @@ try {
96
96
}
97
97
db()->exec('BEGIN IMMEDIATE');
98
98
$out=['ok'=>true];
99
if ($action==='push_subscribe') {
99
if ($action==='claim_notification_intro') {
100
$out['show']=query('INSERT OR IGNORE INTO notification_intro(user_id,seen_at) VALUES(?,?)',[$u,time()])->rowCount()===1;
101
} elseif ($action==='push_subscribe') {
100
102
pushSubscribe($u,$in);
101
103
} elseif ($action==='push_unsubscribe') {
102
104
pushUnsubscribe($u,$in['endpoint']??null);
@@ -76,7 +76,7 @@ try {76
else $invite=['kind'=>$l['kind'],'name'=>$l['name'],'token'=>$l['token']];76
else $invite=['kind'=>$l['kind'],'name'=>$l['name'],'token'=>$l['token']];77
}77
}78
$joined=query('SELECT joined FROM matchmaking WHERE user_id=?',[$u])->fetchColumn();78
$joined=query('SELECT joined FROM matchmaking WHERE user_id=?',[$u])->fetchColumn();79
jsonOut(['user'=>profile($u),'csrf'=>$_SESSION['csrf'],'local'=>localDev(),'friends'=>$friends,'friendRequests'=>$requests,'games'=>array_map(fn($g)=>gameView($g,$u),$games),'invite'=>$invite,'matchmaking'=>$joined===false?null:['status'=>(int)$joined<=time()-86400?'expired':'searching']]);79
jsonOut(['notificationIntroSeen'=>(bool)query('SELECT 1 FROM notification_intro WHERE user_id=?',[$u])->fetchColumn(),'user'=>profile($u),'csrf'=>$_SESSION['csrf'],'local'=>localDev(),'friends'=>$friends,'friendRequests'=>$requests,'games'=>array_map(fn($g)=>gameView($g,$u),$games),'invite'=>$invite,'matchmaking'=>$joined===false?null:['status'=>(int)$joined<=time()-86400?'expired':'searching']]);80
}80
}81
if ($method!=='POST') fail('Method not allowed.',405);81
if ($method!=='POST') fail('Method not allowed.',405);82
if (!hash_equals($_SESSION['csrf']??'',$_SERVER['HTTP_X_CSRF_TOKEN']??'')) fail('Invalid session token. Reload the page.',403);82
if (!hash_equals($_SESSION['csrf']??'',$_SERVER['HTTP_X_CSRF_TOKEN']??'')) fail('Invalid session token. Reload the page.',403);@@ -96,7 +96,9 @@ try {96
}96
}97
db()->exec('BEGIN IMMEDIATE');97
db()->exec('BEGIN IMMEDIATE');98
$out=['ok'=>true];98
$out=['ok'=>true];99
if ($action==='push_subscribe') {99
if ($action==='claim_notification_intro') {100
$out['show']=query('INSERT OR IGNORE INTO notification_intro(user_id,seen_at) VALUES(?,?)',[$u,time()])->rowCount()===1;101
} elseif ($action==='push_subscribe') {100
pushSubscribe($u,$in);102
pushSubscribe($u,$in);101
} elseif ($action==='push_unsubscribe') {103
} elseif ($action==='push_unsubscribe') {102
pushUnsubscribe($u,$in['endpoint']??null);104
pushUnsubscribe($u,$in['endpoint']??null);@@ -1444,3 +1444,9 @@ body.replay-page { min-height: 100dvh; display: grid; place-items: center; paddi
1444
1444
#notification-settings .inline-note { margin-top: .5rem; }
1445
1445
#install-help { font-size: .9rem; }
1446
1446
.login [data-install-app] { display: block; margin: 1rem auto; }
1447
1448
#notification-dialog { max-height: calc(100dvh - 32px); overflow-y: auto; }
1449
#notification-dialog details { margin-top: 16px; font-size: 13px; overflow-wrap: anywhere; }
1450
#notification-dialog summary { cursor: pointer; color: var(--muted); }
1451
#notification-dialog details p { margin: 8px 0 0; }
1452
#notification-dialog #push-settings-page { font-size: 14px; }
@@ -1444,3 +1444,9 @@ body.replay-page { min-height: 100dvh; display: grid; place-items: center; paddi1444
#notification-settings .inline-note { margin-top: .5rem; }1444
#notification-settings .inline-note { margin-top: .5rem; }1445
#install-help { font-size: .9rem; }1445
#install-help { font-size: .9rem; }1446
.login [data-install-app] { display: block; margin: 1rem auto; }1446
.login [data-install-app] { display: block; margin: 1rem auto; }1447
1448
#notification-dialog { max-height: calc(100dvh - 32px); overflow-y: auto; }1449
#notification-dialog details { margin-top: 16px; font-size: 13px; overflow-wrap: anywhere; }1450
#notification-dialog summary { cursor: pointer; color: var(--muted); }1451
#notification-dialog details p { margin: 8px 0 0; }1452
#notification-dialog #push-settings-page { font-size: 14px; }@@ -107,6 +107,7 @@ async function refresh (force = false)
107
107
if (i.error) showModal(`<h2>Invitation</h2><p>${esc(i.error)}</p><button class="primary" data-modal-action="close">Got it</button>`);
108
108
else showModal(`<span class="eyebrow">${i.kind === 'friend' ? 'FRIEND REQUEST' : 'YOU’RE INVITED'}</span><h2>${esc(i.name)} ${i.kind === 'friend' ? 'wants to be friends.' : 'challenges you.'}</h2><p>${i.kind === 'friend' ? 'Accept to add each other to your friends lists.' : 'A fresh board, a friendly rivalry. Ready to play?'}</p><div class="actions"><button class="primary" data-modal-action="accept-invite">Accept</button><button class="secondary" data-modal-action="close">Reject</button></div>`);
109
109
}
110
window.microchessPwa?.intro();
110
111
} catch (e) { toast(e.message || 'Connection lost. We’ll try again shortly.'); }
111
112
}
112
113
function empty (yours) { return `<div class="empty"><span class="empty-icon">♘</span><h3>${yours ? 'Your next rivalry starts here.' : 'All caught up.'}</h3><p>${yours ? 'Challenge a friend or share a game link. Your games and invitations will appear here.' : 'Games appear here while your opponent is thinking.'}</p>${yours ? '<button class="text-button" data-create-link="match">Invite someone to play ↗</button>' : ''}</div>`; }
@@ -107,6 +107,7 @@ async function refresh (force = false)107
if (i.error) showModal(`<h2>Invitation</h2><p>${esc(i.error)}</p><button class="primary" data-modal-action="close">Got it</button>`);107
if (i.error) showModal(`<h2>Invitation</h2><p>${esc(i.error)}</p><button class="primary" data-modal-action="close">Got it</button>`);108
else showModal(`<span class="eyebrow">${i.kind === 'friend' ? 'FRIEND REQUEST' : 'YOU’RE INVITED'}</span><h2>${esc(i.name)} ${i.kind === 'friend' ? 'wants to be friends.' : 'challenges you.'}</h2><p>${i.kind === 'friend' ? 'Accept to add each other to your friends lists.' : 'A fresh board, a friendly rivalry. Ready to play?'}</p><div class="actions"><button class="primary" data-modal-action="accept-invite">Accept</button><button class="secondary" data-modal-action="close">Reject</button></div>`);108
else showModal(`<span class="eyebrow">${i.kind === 'friend' ? 'FRIEND REQUEST' : 'YOU’RE INVITED'}</span><h2>${esc(i.name)} ${i.kind === 'friend' ? 'wants to be friends.' : 'challenges you.'}</h2><p>${i.kind === 'friend' ? 'Accept to add each other to your friends lists.' : 'A fresh board, a friendly rivalry. Ready to play?'}</p><div class="actions"><button class="primary" data-modal-action="accept-invite">Accept</button><button class="secondary" data-modal-action="close">Reject</button></div>`);109
}109
}110
window.microchessPwa?.intro();110
} catch (e) { toast(e.message || 'Connection lost. We’ll try again shortly.'); }111
} catch (e) { toast(e.message || 'Connection lost. We’ll try again shortly.'); }111
}112
}112
function empty (yours) { return `<div class="empty"><span class="empty-icon">♘</span><h3>${yours ? 'Your next rivalry starts here.' : 'All caught up.'}</h3><p>${yours ? 'Challenge a friend or share a game link. Your games and invitations will appear here.' : 'Games appear here while your opponent is thinking.'}</p>${yours ? '<button class="text-button" data-create-link="match">Invite someone to play ↗</button>' : ''}</div>`; }113
function empty (yours) { return `<div class="empty"><span class="empty-icon">♘</span><h3>${yours ? 'Your next rivalry starts here.' : 'All caught up.'}</h3><p>${yours ? 'Challenge a friend or share a game link. Your games and invitations will appear here.' : 'Games appear here while your opponent is thinking.'}</p>${yours ? '<button class="text-button" data-create-link="match">Invite someone to play ↗</button>' : ''}</div>`; }@@ -4,7 +4,9 @@
4
4
const supported = 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window;
5
5
const standalone = () => matchMedia('(display-mode: standalone)').matches || navigator.standalone === true;
6
6
const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;
7
let installPrompt, syncedUser, enabled = false, operation = false;
7
let installPrompt, syncedUser, enabled = false, operation = false, introRequest = false, pendingIntro;
8
const introHandled = new Set();
9
const notice = document.querySelector('#notification-dialog');
8
10
let target = new URLSearchParams(location.search).get('game'), highlightUntil = 0;
9
11
if (!/^[1-9][0-9]{0,14}$/.test(target || '')) target = null;
10
12
const registration = 'serviceWorker' in navigator ? navigator.serviceWorker.register('sw.js').catch(() => null) : Promise.resolve(null);
@@ -30,9 +32,71 @@
30
32
if (Notification.permission === 'denied') { el.innerHTML = '<p>Notifications are blocked. Allow them in your browser or device settings, then reopen Microchess.</p>'; return; }
31
33
el.innerHTML = `<button class="secondary" data-toggle-push ${operation ? 'disabled' : ''}>${enabled ? 'Disable' : 'Enable'} turn notifications</button><p class="inline-note">On this device, for turns, challenges and rematch requests.</p>`;
32
34
}
35
function showNotice (title, content, kind)
36
{
37
if (!notice) return;
38
notice.dataset.kind = kind;
39
document.querySelector('#notification-dialog-content').innerHTML = `<h2 id="notification-dialog-title">${esc(title)}</h2>${content}<div class="actions"><button class="primary" data-close-notification-dialog autofocus>Got it</button></div>`;
40
if (!notice.open) notice.showModal();
41
}
42
async function intro ()
43
{
44
if (!notice || !state || document.hidden || modal?.open || notice.open || introRequest || busy) return;
45
const user = state.user.id;
46
if (pendingIntro === user) {
47
pendingIntro = null;
48
showNotice('Turn notifications', `<p>Do you want to be notified when it's your turn? Enable the Notification setting in the Account Settings panel at the top right of the page.</p>`, 'intro');
49
return;
50
}
51
if (state.notificationIntroSeen || introHandled.has(user)) return;
52
introRequest = true;
53
try {
54
// An atomic claim prevents the same account seeing this in two tabs/devices.
55
const result = await api({ action: 'claim_notification_intro' });
56
introHandled.add(user);
57
if (result.show) pendingIntro = user;
58
if (state.user.id === user) state.notificationIntroSeen = true;
59
} catch (_) { /* Try again on a later state refresh; game play remains available. */ }
60
finally { introRequest = false; }
61
if (pendingIntro === state?.user.id) intro();
62
}
63
async function notificationFailure (error, phase, disabling)
64
{
65
let advice;
66
if (phase === 'subscribe' && (error.name === 'AbortError' || /push service error/i.test(error.message || ''))) {
67
let brave = false;
68
try { brave = await navigator.brave?.isBrave() || false; } catch (_) {}
69
advice = `<p>The browser could not register with its push service. ${brave ? 'This may be due to Brave’s “Use Google services for push messaging” setting being turned off.' : 'This may be due to a disabled browser push service or a network connection blocking it.'}</p><p>${brave ? 'Open this page in Brave' : 'If you use Brave, open this page'}, turn on <strong>Use Google services for push messaging</strong>, fully restart Brave, then try enabling notifications again.</p><input id="push-settings-page" value="brave://settings/privacy" aria-label="Brave settings page" readonly><button class="text-button" data-copy-push-settings>Copy address</button><p>Allowing notifications for Microchess alone does not enable that browser service. If the setting is already on, try again on another network or check your VPN/firewall settings.</p>`;
70
} else if (phase === 'permission' || error.name === 'NotAllowedError') {
71
advice = '<p>Notification permission was not granted. Allow notifications for this site in your browser or device settings, then try again.</p>';
72
} else if (phase === 'subscribe') {
73
advice = '<p>The browser could not set up notifications. This may be due to its push service or a connection problem. Restart your browser and try again. On iPhone or iPad, open Microchess from its home-screen icon.</p>';
74
} else {
75
advice = '<p>Microchess could not save your notification settings. This may be due to a connection problem or an expired sign-in session. Reload the page, sign in if asked, and try again.</p>';
76
}
77
const details = error.message ? `<details><summary>Error details</summary><p>${esc(error.message)}</p></details>` : '';
78
showNotice(disabling ? 'Disabling notifications failed' : 'Enabling notifications failed', advice + details, 'error');
79
}
80
notice?.addEventListener('click', event => {
81
if (event.target.closest('[data-close-notification-dialog]')) notice.close();
82
if (event.target === notice) {
83
const rect = notice.getBoundingClientRect();
84
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) notice.close();
85
}
86
});
87
// Escape closes only this top dialog, without resetting the game/account behind it.
88
notice?.addEventListener('keydown', event => { if (event.key === 'Escape') event.stopPropagation(); });
89
notice?.addEventListener('close', () => {
90
if (modal?.open) (document.querySelector('[data-toggle-push]') || document.querySelector('#modal-close'))?.focus();
91
intro();
92
});
93
modal?.addEventListener('close', () => intro());
94
document.addEventListener('visibilitychange', () => { if (!document.hidden) intro(); });
33
95
async function toggle ()
34
96
{
35
97
if (operation || !state) return;
98
const disabling = enabled;
99
let phase = disabling ? 'save' : 'permission';
36
100
operation = true; settings();
37
101
try {
38
102
if (enabled) {
@@ -42,20 +106,23 @@
42
106
} else {
43
107
// Call permission directly from the button gesture (required on iOS).
44
108
const permission = await Notification.requestPermission();
45
if (permission !== 'granted') { toast('Notifications were not enabled.'); return; }
109
if (permission !== 'granted') { await notificationFailure(new Error('Notifications were not enabled.'), phase, false); return; }
110
phase = 'config';
46
111
const response = await fetch('api.php?action=push_config');
47
112
const config = await response.json();
48
113
if (!response.ok) throw new Error(config.error || 'Unable to enable notifications.');
114
phase = 'subscribe';
49
115
const reg = await registration;
50
116
if (!reg) throw new Error('Unable to register notifications. Reload and try again.');
51
117
await navigator.serviceWorker.ready;
52
118
const key = Uint8Array.from(atob(config.publicKey.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0));
53
119
const sub = await reg.pushManager.getSubscription() || await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key });
120
phase = 'save';
54
121
await api({ action: 'push_subscribe', subscription: sub.toJSON() });
55
122
enabled = true;
56
123
}
57
124
toast(enabled ? 'Turn notifications enabled on this device.' : 'Turn notifications disabled on this device.');
58
} catch (error) { toast(error.message || 'Unable to change notifications.'); }
125
} catch (error) { await notificationFailure(error, phase, disabling); }
59
126
finally { operation = false; settings(); }
60
127
}
61
128
function highlight ()
@@ -80,12 +147,18 @@
80
147
window.addEventListener('appinstalled', () => { installPrompt = null; document.querySelectorAll('[data-install-app]').forEach(button => { button.hidden = true; }); });
81
148
document.addEventListener('click', async event =>
82
149
{
150
if (event.target.closest('[data-copy-push-settings]')) {
151
const input = document.querySelector('#push-settings-page');
152
try { await navigator.clipboard.writeText(input.value); event.target.textContent = 'Copied ✓'; }
153
catch (_) { input.focus(); input.select(); }
154
return;
155
}
83
156
if (event.target.closest('[data-toggle-push]')) await toggle();
84
157
if (!event.target.closest('[data-install-app]')) return;
85
158
if (installPrompt) { const prompt = installPrompt; installPrompt = null; await prompt.prompt(); await prompt.userChoice; return; }
86
159
const help = document.querySelector('#install-help');
87
160
if (help) { help.hidden = false; help.textContent = standalone() ? 'Microchess is already running as an app.' : ios ? 'Open the Share menu, choose Add to Home Screen, and open Microchess using its new icon. Sign in there if asked.' : 'Open your browser menu and choose Install app or Add to Home screen. If this option is missing, try opening Microchess in Chrome or Safari.'; }
88
161
});
89
window.microchessPwa = { sync, settings, highlight, endpoint };
90
if (typeof state !== 'undefined' && state) { sync(); highlight(); }
162
window.microchessPwa = { sync, settings, highlight, endpoint, intro };
163
if (typeof state !== 'undefined' && state) { sync(); highlight(); intro(); }
91
164
})();
@@ -4,7 +4,9 @@4
const supported = 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window;4
const supported = 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window;5
const standalone = () => matchMedia('(display-mode: standalone)').matches || navigator.standalone === true;5
const standalone = () => matchMedia('(display-mode: standalone)').matches || navigator.standalone === true;6
const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;6
const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;7
let installPrompt, syncedUser, enabled = false, operation = false;7
let installPrompt, syncedUser, enabled = false, operation = false, introRequest = false, pendingIntro;8
const introHandled = new Set();9
const notice = document.querySelector('#notification-dialog');8
let target = new URLSearchParams(location.search).get('game'), highlightUntil = 0;10
let target = new URLSearchParams(location.search).get('game'), highlightUntil = 0;9
if (!/^[1-9][0-9]{0,14}$/.test(target || '')) target = null;11
if (!/^[1-9][0-9]{0,14}$/.test(target || '')) target = null;10
const registration = 'serviceWorker' in navigator ? navigator.serviceWorker.register('sw.js').catch(() => null) : Promise.resolve(null);12
const registration = 'serviceWorker' in navigator ? navigator.serviceWorker.register('sw.js').catch(() => null) : Promise.resolve(null);@@ -30,9 +32,71 @@30
if (Notification.permission === 'denied') { el.innerHTML = '<p>Notifications are blocked. Allow them in your browser or device settings, then reopen Microchess.</p>'; return; }32
if (Notification.permission === 'denied') { el.innerHTML = '<p>Notifications are blocked. Allow them in your browser or device settings, then reopen Microchess.</p>'; return; }31
el.innerHTML = `<button class="secondary" data-toggle-push ${operation ? 'disabled' : ''}>${enabled ? 'Disable' : 'Enable'} turn notifications</button><p class="inline-note">On this device, for turns, challenges and rematch requests.</p>`;33
el.innerHTML = `<button class="secondary" data-toggle-push ${operation ? 'disabled' : ''}>${enabled ? 'Disable' : 'Enable'} turn notifications</button><p class="inline-note">On this device, for turns, challenges and rematch requests.</p>`;32
}34
}35
function showNotice (title, content, kind)36
{37
if (!notice) return;38
notice.dataset.kind = kind;39
document.querySelector('#notification-dialog-content').innerHTML = `<h2 id="notification-dialog-title">${esc(title)}</h2>${content}<div class="actions"><button class="primary" data-close-notification-dialog autofocus>Got it</button></div>`;40
if (!notice.open) notice.showModal();41
}42
async function intro ()43
{44
if (!notice || !state || document.hidden || modal?.open || notice.open || introRequest || busy) return;45
const user = state.user.id;46
if (pendingIntro === user) {47
pendingIntro = null;48
showNotice('Turn notifications', `<p>Do you want to be notified when it's your turn? Enable the Notification setting in the Account Settings panel at the top right of the page.</p>`, 'intro');49
return;50
}51
if (state.notificationIntroSeen || introHandled.has(user)) return;52
introRequest = true;53
try {54
// An atomic claim prevents the same account seeing this in two tabs/devices.55
const result = await api({ action: 'claim_notification_intro' });56
introHandled.add(user);57
if (result.show) pendingIntro = user;58
if (state.user.id === user) state.notificationIntroSeen = true;59
} catch (_) { /* Try again on a later state refresh; game play remains available. */ }60
finally { introRequest = false; }61
if (pendingIntro === state?.user.id) intro();62
}63
async function notificationFailure (error, phase, disabling)64
{65
let advice;66
if (phase === 'subscribe' && (error.name === 'AbortError' || /push service error/i.test(error.message || ''))) {67
let brave = false;68
try { brave = await navigator.brave?.isBrave() || false; } catch (_) {}69
advice = `<p>The browser could not register with its push service. ${brave ? 'This may be due to Brave’s “Use Google services for push messaging” setting being turned off.' : 'This may be due to a disabled browser push service or a network connection blocking it.'}</p><p>${brave ? 'Open this page in Brave' : 'If you use Brave, open this page'}, turn on <strong>Use Google services for push messaging</strong>, fully restart Brave, then try enabling notifications again.</p><input id="push-settings-page" value="brave://settings/privacy" aria-label="Brave settings page" readonly><button class="text-button" data-copy-push-settings>Copy address</button><p>Allowing notifications for Microchess alone does not enable that browser service. If the setting is already on, try again on another network or check your VPN/firewall settings.</p>`;70
} else if (phase === 'permission' || error.name === 'NotAllowedError') {71
advice = '<p>Notification permission was not granted. Allow notifications for this site in your browser or device settings, then try again.</p>';72
} else if (phase === 'subscribe') {73
advice = '<p>The browser could not set up notifications. This may be due to its push service or a connection problem. Restart your browser and try again. On iPhone or iPad, open Microchess from its home-screen icon.</p>';74
} else {75
advice = '<p>Microchess could not save your notification settings. This may be due to a connection problem or an expired sign-in session. Reload the page, sign in if asked, and try again.</p>';76
}77
const details = error.message ? `<details><summary>Error details</summary><p>${esc(error.message)}</p></details>` : '';78
showNotice(disabling ? 'Disabling notifications failed' : 'Enabling notifications failed', advice + details, 'error');79
}80
notice?.addEventListener('click', event => {81
if (event.target.closest('[data-close-notification-dialog]')) notice.close();82
if (event.target === notice) {83
const rect = notice.getBoundingClientRect();84
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) notice.close();85
}86
});87
// Escape closes only this top dialog, without resetting the game/account behind it.88
notice?.addEventListener('keydown', event => { if (event.key === 'Escape') event.stopPropagation(); });89
notice?.addEventListener('close', () => {90
if (modal?.open) (document.querySelector('[data-toggle-push]') || document.querySelector('#modal-close'))?.focus();91
intro();92
});93
modal?.addEventListener('close', () => intro());94
document.addEventListener('visibilitychange', () => { if (!document.hidden) intro(); });33
async function toggle ()95
async function toggle ()34
{96
{35
if (operation || !state) return;97
if (operation || !state) return;98
const disabling = enabled;99
let phase = disabling ? 'save' : 'permission';36
operation = true; settings();100
operation = true; settings();37
try {101
try {38
if (enabled) {102
if (enabled) {@@ -42,20 +106,23 @@42
} else {106
} else {43
// Call permission directly from the button gesture (required on iOS).107
// Call permission directly from the button gesture (required on iOS).44
const permission = await Notification.requestPermission();108
const permission = await Notification.requestPermission();45
if (permission !== 'granted') { toast('Notifications were not enabled.'); return; }109
if (permission !== 'granted') { await notificationFailure(new Error('Notifications were not enabled.'), phase, false); return; }110
phase = 'config';46
const response = await fetch('api.php?action=push_config');111
const response = await fetch('api.php?action=push_config');47
const config = await response.json();112
const config = await response.json();48
if (!response.ok) throw new Error(config.error || 'Unable to enable notifications.');113
if (!response.ok) throw new Error(config.error || 'Unable to enable notifications.');114
phase = 'subscribe';49
const reg = await registration;115
const reg = await registration;50
if (!reg) throw new Error('Unable to register notifications. Reload and try again.');116
if (!reg) throw new Error('Unable to register notifications. Reload and try again.');51
await navigator.serviceWorker.ready;117
await navigator.serviceWorker.ready;52
const key = Uint8Array.from(atob(config.publicKey.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0));118
const key = Uint8Array.from(atob(config.publicKey.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0));53
const sub = await reg.pushManager.getSubscription() || await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key });119
const sub = await reg.pushManager.getSubscription() || await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key });120
phase = 'save';54
await api({ action: 'push_subscribe', subscription: sub.toJSON() });121
await api({ action: 'push_subscribe', subscription: sub.toJSON() });55
enabled = true;122
enabled = true;56
}123
}57
toast(enabled ? 'Turn notifications enabled on this device.' : 'Turn notifications disabled on this device.');124
toast(enabled ? 'Turn notifications enabled on this device.' : 'Turn notifications disabled on this device.');58
} catch (error) { toast(error.message || 'Unable to change notifications.'); }125
} catch (error) { await notificationFailure(error, phase, disabling); }59
finally { operation = false; settings(); }126
finally { operation = false; settings(); }60
}127
}61
function highlight ()128
function highlight ()@@ -80,12 +147,18 @@80
window.addEventListener('appinstalled', () => { installPrompt = null; document.querySelectorAll('[data-install-app]').forEach(button => { button.hidden = true; }); });147
window.addEventListener('appinstalled', () => { installPrompt = null; document.querySelectorAll('[data-install-app]').forEach(button => { button.hidden = true; }); });81
document.addEventListener('click', async event =>148
document.addEventListener('click', async event =>82
{149
{150
if (event.target.closest('[data-copy-push-settings]')) {151
const input = document.querySelector('#push-settings-page');152
try { await navigator.clipboard.writeText(input.value); event.target.textContent = 'Copied ✓'; }153
catch (_) { input.focus(); input.select(); }154
return;155
}83
if (event.target.closest('[data-toggle-push]')) await toggle();156
if (event.target.closest('[data-toggle-push]')) await toggle();84
if (!event.target.closest('[data-install-app]')) return;157
if (!event.target.closest('[data-install-app]')) return;85
if (installPrompt) { const prompt = installPrompt; installPrompt = null; await prompt.prompt(); await prompt.userChoice; return; }158
if (installPrompt) { const prompt = installPrompt; installPrompt = null; await prompt.prompt(); await prompt.userChoice; return; }86
const help = document.querySelector('#install-help');159
const help = document.querySelector('#install-help');87
if (help) { help.hidden = false; help.textContent = standalone() ? 'Microchess is already running as an app.' : ios ? 'Open the Share menu, choose Add to Home Screen, and open Microchess using its new icon. Sign in there if asked.' : 'Open your browser menu and choose Install app or Add to Home screen. If this option is missing, try opening Microchess in Chrome or Safari.'; }160
if (help) { help.hidden = false; help.textContent = standalone() ? 'Microchess is already running as an app.' : ios ? 'Open the Share menu, choose Add to Home Screen, and open Microchess using its new icon. Sign in there if asked.' : 'Open your browser menu and choose Install app or Add to Home screen. If this option is missing, try opening Microchess in Chrome or Safari.'; }88
});161
});89
window.microchessPwa = { sync, settings, highlight, endpoint };162
window.microchessPwa = { sync, settings, highlight, endpoint, intro };90
if (typeof state !== 'undefined' && state) { sync(); highlight(); }163
if (typeof state !== 'undefined' && state) { sync(); highlight(); intro(); }91
})();164
})();@@ -34,6 +34,7 @@ $loginQuery=http_build_query(array_filter(['invite'=>$invite,'game'=>$game]));
34
34
<div id="sidebar-backdrop" hidden></div><aside id="sidebar" aria-label="Friends"><div class="sidebar-heading"><h2>Your people<span class="brand-dot">.</span></h2><button id="friends-close" class="quiet" aria-label="Close friends">✕</button></div><button id="friend-link" class="invite-friend">+ Invite a friend <span>↗</span></button><div class="friends-label">FRIENDS <span id="sidebar-count">0</span></div><div id="friend-list"></div><div id="friend-requests"></div><div class="sidebar-note"><span>♘</span><h3>Better with a rival.</h3><p>Invite a friend, make your move.<br>Come back for the rematch.</p></div><div id="account-summary"></div></aside></div>
35
35
<?php endif ?>
36
36
<?php if (!$sharedReplay): ?>
37
<dialog id="notification-dialog" aria-labelledby="notification-dialog-title"><button class="modal-close quiet" data-close-notification-dialog aria-label="Close dialog">✕</button><div id="notification-dialog-content"></div></dialog>
37
38
<dialog id="modal" aria-labelledby="modal-title"><button id="modal-close" class="modal-close quiet" aria-label="Close dialog">✕</button><div id="modal-content"></div></dialog>
38
39
<?php endif ?>
39
40
<div id="toast" role="status" aria-live="polite"></div>
@@ -34,6 +34,7 @@ $loginQuery=http_build_query(array_filter(['invite'=>$invite,'game'=>$game]));34
<div id="sidebar-backdrop" hidden></div><aside id="sidebar" aria-label="Friends"><div class="sidebar-heading"><h2>Your people<span class="brand-dot">.</span></h2><button id="friends-close" class="quiet" aria-label="Close friends">✕</button></div><button id="friend-link" class="invite-friend">+ Invite a friend <span>↗</span></button><div class="friends-label">FRIENDS <span id="sidebar-count">0</span></div><div id="friend-list"></div><div id="friend-requests"></div><div class="sidebar-note"><span>♘</span><h3>Better with a rival.</h3><p>Invite a friend, make your move.<br>Come back for the rematch.</p></div><div id="account-summary"></div></aside></div>34
<div id="sidebar-backdrop" hidden></div><aside id="sidebar" aria-label="Friends"><div class="sidebar-heading"><h2>Your people<span class="brand-dot">.</span></h2><button id="friends-close" class="quiet" aria-label="Close friends">✕</button></div><button id="friend-link" class="invite-friend">+ Invite a friend <span>↗</span></button><div class="friends-label">FRIENDS <span id="sidebar-count">0</span></div><div id="friend-list"></div><div id="friend-requests"></div><div class="sidebar-note"><span>♘</span><h3>Better with a rival.</h3><p>Invite a friend, make your move.<br>Come back for the rematch.</p></div><div id="account-summary"></div></aside></div>35
<?php endif ?>35
<?php endif ?>36
<?php if (!$sharedReplay): ?>36
<?php if (!$sharedReplay): ?>37
<dialog id="notification-dialog" aria-labelledby="notification-dialog-title"><button class="modal-close quiet" data-close-notification-dialog aria-label="Close dialog">✕</button><div id="notification-dialog-content"></div></dialog>37
<dialog id="modal" aria-labelledby="modal-title"><button id="modal-close" class="modal-close quiet" aria-label="Close dialog">✕</button><div id="modal-content"></div></dialog>38
<dialog id="modal" aria-labelledby="modal-title"><button id="modal-close" class="modal-close quiet" aria-label="Close dialog">✕</button><div id="modal-content"></div></dialog>38
<?php endif ?>39
<?php endif ?>39
<div id="toast" role="status" aria-live="polite"></div>40
<div id="toast" role="status" aria-live="polite"></div>@@ -26,6 +26,7 @@ function db(): PDO {
26
26
CREATE TABLE IF NOT EXISTS results (id INTEGER PRIMARY KEY AUTOINCREMENT, game_id INTEGER NOT NULL REFERENCES games(id), a TEXT NOT NULL, b TEXT NOT NULL, winner TEXT, reason TEXT NOT NULL, state TEXT NOT NULL, ended INTEGER NOT NULL);
27
27
CREATE INDEX IF NOT EXISTS games_a ON games(a); CREATE INDEX IF NOT EXISTS games_b ON games(b);');
28
28
$db->exec('CREATE TABLE IF NOT EXISTS push_subscriptions (endpoint TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id), p256dh TEXT NOT NULL, auth TEXT NOT NULL, updated INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS push_user ON push_subscriptions(user_id);');
29
$db->exec('CREATE TABLE IF NOT EXISTS notification_intro (user_id TEXT PRIMARY KEY REFERENCES users(id), seen_at INTEGER NOT NULL);');
29
30
$columns=$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1);
30
31
if (!in_array('activity_at',$columns,true)) {
31
32
$db->exec('BEGIN IMMEDIATE');
@@ -26,6 +26,7 @@ function db(): PDO {26
CREATE TABLE IF NOT EXISTS results (id INTEGER PRIMARY KEY AUTOINCREMENT, game_id INTEGER NOT NULL REFERENCES games(id), a TEXT NOT NULL, b TEXT NOT NULL, winner TEXT, reason TEXT NOT NULL, state TEXT NOT NULL, ended INTEGER NOT NULL);26
CREATE TABLE IF NOT EXISTS results (id INTEGER PRIMARY KEY AUTOINCREMENT, game_id INTEGER NOT NULL REFERENCES games(id), a TEXT NOT NULL, b TEXT NOT NULL, winner TEXT, reason TEXT NOT NULL, state TEXT NOT NULL, ended INTEGER NOT NULL);27
CREATE INDEX IF NOT EXISTS games_a ON games(a); CREATE INDEX IF NOT EXISTS games_b ON games(b);');27
CREATE INDEX IF NOT EXISTS games_a ON games(a); CREATE INDEX IF NOT EXISTS games_b ON games(b);');28
$db->exec('CREATE TABLE IF NOT EXISTS push_subscriptions (endpoint TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id), p256dh TEXT NOT NULL, auth TEXT NOT NULL, updated INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS push_user ON push_subscriptions(user_id);');28
$db->exec('CREATE TABLE IF NOT EXISTS push_subscriptions (endpoint TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id), p256dh TEXT NOT NULL, auth TEXT NOT NULL, updated INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS push_user ON push_subscriptions(user_id);');29
$db->exec('CREATE TABLE IF NOT EXISTS notification_intro (user_id TEXT PRIMARY KEY REFERENCES users(id), seen_at INTEGER NOT NULL);');29
$columns=$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1);30
$columns=$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1);30
if (!in_array('activity_at',$columns,true)) {31
if (!in_array('activity_at',$columns,true)) {31
$db->exec('BEGIN IMMEDIATE');32
$db->exec('BEGIN IMMEDIATE');@@ -19,7 +19,46 @@ try{
19
19
const ca=await browser.newContext({viewport:{width:1440,height:1080}}),cb=await browser.newContext({viewport:{width:1440,height:1080}});
20
20
const a=await ca.newPage(),b=await cb.newPage(),errors=[];
21
21
for(const p of[a,b]){p.on('pageerror',e=>errors.push(e.message));p.on('console',m=>{if(m.type()==='error')errors.push(m.text());});}
22
await a.goto(base);await b.goto(base);
22
await a.goto(base);
23
const intro=a.locator('#notification-dialog');
24
await intro.waitFor({state:'visible'});
25
assert.equal(await intro.locator('p').innerText(),"Do you want to be notified when it's your turn? Enable the Notification setting in the Account Settings panel at the top right of the page.",'Exact once-only notification introduction');
26
await intro.getByRole('button',{name:'Got it',exact:true}).click();
27
await a.reload();await a.locator('#avatar-button').waitFor();
28
assert.equal(await intro.isVisible(),false,'Introduction stays dismissed after reload');
29
await b.goto(base);await b.locator('#avatar-button').waitFor();
30
assert.equal(await b.locator('#notification-dialog').isVisible(),false,'Introduction is remembered across browser profiles');
31
await a.evaluate(()=>{
32
const request=Notification.requestPermission,subscribe=PushManager.prototype.subscribe,permission=Object.getOwnPropertyDescriptor(Notification,'permission');
33
window.restoreNotificationMocks=()=>{Notification.requestPermission=request;PushManager.prototype.subscribe=subscribe;Object.defineProperty(Notification,'permission',permission);delete navigator.brave;};
34
Object.defineProperty(Notification,'permission',{get:()=>'granted',configurable:true});
35
Notification.requestPermission=async()=>'granted';
36
PushManager.prototype.subscribe=async()=>{throw new DOMException('Registration failed - push service error','AbortError');};
37
Object.defineProperty(navigator,'brave',{value:{isBrave:async()=>true},configurable:true});
38
});
39
await a.locator('#settings-button').click();
40
await a.locator('[data-toggle-push]').click();
41
await intro.getByRole('heading',{name:'Enabling notifications failed'}).waitFor();
42
assert((await intro.innerText()).includes('This may be due to Brave'),'Brave advice does not assert an unproven cause');
43
assert.equal(await intro.locator('#push-settings-page').inputValue(),'brave://settings/privacy','Concrete Brave settings page');
44
assert((await intro.innerText()).includes('Use Google services for push messaging'),'Concrete Brave setting');
45
assert(await a.locator('#modal').evaluate(el=>el.open),'Account dialog remains open underneath error');
46
await a.screenshot({path:path.join(web,'tests/artifacts/notification-error-desktop.png')});
47
await a.keyboard.press('Escape');
48
await intro.waitFor({state:'hidden'});
49
assert(await a.locator('#modal').evaluate(el=>el.open),'Escape only closes the top dialog');
50
assert(await a.locator('[data-toggle-push]').evaluate(el=>el===document.activeElement),'Focus returns to notification setting');
51
await a.evaluate(()=>{navigator.brave.isBrave=async()=>false;});
52
await a.locator('[data-toggle-push]').click();
53
await intro.getByRole('heading',{name:'Enabling notifications failed'}).waitFor();
54
assert((await intro.innerText()).includes('If you use Brave'),'Other browsers get conditional Brave advice');
55
await a.setViewportSize({width:390,height:844});
56
assert(await intro.evaluate(el=>el.getBoundingClientRect().width<=innerWidth),'Error fits a mobile viewport');
57
await a.screenshot({path:path.join(web,'tests/artifacts/notification-error-mobile.png')});
58
await intro.getByRole('button',{name:'Got it',exact:true}).click();
59
await a.setViewportSize({width:1440,height:1080});
60
await a.evaluate(()=>window.restoreNotificationMocks());
61
await a.locator('#modal-close').click();
23
62
await a.locator('#avatar-button').click();
24
63
await a.locator('[data-avatar-choice="blue-knight"]').waitFor();
25
64
await a.locator('[data-avatar-group="fairy"]').click();
@@ -42,6 +81,7 @@ try{
42
81
await a.reload();await a.locator('#avatar-button img[src$="blue-knight.png"]').waitFor();
43
82
await b.locator('#settings-button').click();await b.getByRole('button',{name:'Switch to test_user_2'}).click();
44
83
await b.locator('#account-summary').getByText('test_user_2',{exact:false}).waitFor();
84
await b.locator('#notification-dialog').getByRole('button',{name:'Got it',exact:true}).click();
45
85
await a.locator('#friend-link').click();await a.locator('#share-url').waitFor();
46
86
const friendLink=await a.locator('#share-url').inputValue();
47
87
await a.locator('#modal-close').click();
@@ -19,7 +19,46 @@ try{19
const ca=await browser.newContext({viewport:{width:1440,height:1080}}),cb=await browser.newContext({viewport:{width:1440,height:1080}});19
const ca=await browser.newContext({viewport:{width:1440,height:1080}}),cb=await browser.newContext({viewport:{width:1440,height:1080}});20
const a=await ca.newPage(),b=await cb.newPage(),errors=[];20
const a=await ca.newPage(),b=await cb.newPage(),errors=[];21
for(const p of[a,b]){p.on('pageerror',e=>errors.push(e.message));p.on('console',m=>{if(m.type()==='error')errors.push(m.text());});}21
for(const p of[a,b]){p.on('pageerror',e=>errors.push(e.message));p.on('console',m=>{if(m.type()==='error')errors.push(m.text());});}22
await a.goto(base);await b.goto(base);22
await a.goto(base);23
const intro=a.locator('#notification-dialog');24
await intro.waitFor({state:'visible'});25
assert.equal(await intro.locator('p').innerText(),"Do you want to be notified when it's your turn? Enable the Notification setting in the Account Settings panel at the top right of the page.",'Exact once-only notification introduction');26
await intro.getByRole('button',{name:'Got it',exact:true}).click();27
await a.reload();await a.locator('#avatar-button').waitFor();28
assert.equal(await intro.isVisible(),false,'Introduction stays dismissed after reload');29
await b.goto(base);await b.locator('#avatar-button').waitFor();30
assert.equal(await b.locator('#notification-dialog').isVisible(),false,'Introduction is remembered across browser profiles');31
await a.evaluate(()=>{32
const request=Notification.requestPermission,subscribe=PushManager.prototype.subscribe,permission=Object.getOwnPropertyDescriptor(Notification,'permission');33
window.restoreNotificationMocks=()=>{Notification.requestPermission=request;PushManager.prototype.subscribe=subscribe;Object.defineProperty(Notification,'permission',permission);delete navigator.brave;};34
Object.defineProperty(Notification,'permission',{get:()=>'granted',configurable:true});35
Notification.requestPermission=async()=>'granted';36
PushManager.prototype.subscribe=async()=>{throw new DOMException('Registration failed - push service error','AbortError');};37
Object.defineProperty(navigator,'brave',{value:{isBrave:async()=>true},configurable:true});38
});39
await a.locator('#settings-button').click();40
await a.locator('[data-toggle-push]').click();41
await intro.getByRole('heading',{name:'Enabling notifications failed'}).waitFor();42
assert((await intro.innerText()).includes('This may be due to Brave'),'Brave advice does not assert an unproven cause');43
assert.equal(await intro.locator('#push-settings-page').inputValue(),'brave://settings/privacy','Concrete Brave settings page');44
assert((await intro.innerText()).includes('Use Google services for push messaging'),'Concrete Brave setting');45
assert(await a.locator('#modal').evaluate(el=>el.open),'Account dialog remains open underneath error');46
await a.screenshot({path:path.join(web,'tests/artifacts/notification-error-desktop.png')});47
await a.keyboard.press('Escape');48
await intro.waitFor({state:'hidden'});49
assert(await a.locator('#modal').evaluate(el=>el.open),'Escape only closes the top dialog');50
assert(await a.locator('[data-toggle-push]').evaluate(el=>el===document.activeElement),'Focus returns to notification setting');51
await a.evaluate(()=>{navigator.brave.isBrave=async()=>false;});52
await a.locator('[data-toggle-push]').click();53
await intro.getByRole('heading',{name:'Enabling notifications failed'}).waitFor();54
assert((await intro.innerText()).includes('If you use Brave'),'Other browsers get conditional Brave advice');55
await a.setViewportSize({width:390,height:844});56
assert(await intro.evaluate(el=>el.getBoundingClientRect().width<=innerWidth),'Error fits a mobile viewport');57
await a.screenshot({path:path.join(web,'tests/artifacts/notification-error-mobile.png')});58
await intro.getByRole('button',{name:'Got it',exact:true}).click();59
await a.setViewportSize({width:1440,height:1080});60
await a.evaluate(()=>window.restoreNotificationMocks());61
await a.locator('#modal-close').click();23
await a.locator('#avatar-button').click();62
await a.locator('#avatar-button').click();24
await a.locator('[data-avatar-choice="blue-knight"]').waitFor();63
await a.locator('[data-avatar-choice="blue-knight"]').waitFor();25
await a.locator('[data-avatar-group="fairy"]').click();64
await a.locator('[data-avatar-group="fairy"]').click();@@ -42,6 +81,7 @@ try{42
await a.reload();await a.locator('#avatar-button img[src$="blue-knight.png"]').waitFor();81
await a.reload();await a.locator('#avatar-button img[src$="blue-knight.png"]').waitFor();43
await b.locator('#settings-button').click();await b.getByRole('button',{name:'Switch to test_user_2'}).click();82
await b.locator('#settings-button').click();await b.getByRole('button',{name:'Switch to test_user_2'}).click();44
await b.locator('#account-summary').getByText('test_user_2',{exact:false}).waitFor();83
await b.locator('#account-summary').getByText('test_user_2',{exact:false}).waitFor();84
await b.locator('#notification-dialog').getByRole('button',{name:'Got it',exact:true}).click();45
await a.locator('#friend-link').click();await a.locator('#share-url').waitFor();85
await a.locator('#friend-link').click();await a.locator('#share-url').waitFor();46
const friendLink=await a.locator('#share-url').inputValue();86
const friendLink=await a.locator('#share-url').inputValue();47
await a.locator('#modal-close').click();87
await a.locator('#modal-close').click();@@ -90,6 +90,17 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:
90
90
check(json.loads(loaded)=={'base_url':'https://example.test','client_id':'fixture-client','client_secret':'fixture-secret'},'Empty fields use environment; configured fields take precedence')
91
91
b.state(); b.post('switch_user', user='test_user_2'); b.state()
92
92
check(b.state()['user']['name'] == 'test_user_2', 'Independent sessions')
93
check(a.state()['notificationIntroSeen'] is False,'New account has not seen notification introduction')
94
csrf=a.csrf;a.csrf='wrong';a.post('claim_notification_intro',expected=403);a.csrf=csrf
95
check(a.state()['notificationIntroSeen'] is False,'Invalid CSRF cannot consume introduction')
96
same_user=Client();same_user.state()
97
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
98
claims=list(executor.map(lambda client:client.post('claim_notification_intro'),[a,same_user]))
99
check(sum(claim['show'] for claim in claims)==1,'Exactly one concurrent session claims the introduction')
100
check(a.state()['notificationIntroSeen'] is True and same_user.state()['notificationIntroSeen'] is True,'Seen state persists across sessions')
101
check(a.post('claim_notification_intro')['show'] is False,'Introduction cannot be shown again')
102
check(b.state()['notificationIntroSeen'] is False,'Introduction state belongs to the account')
103
check(b.post('claim_notification_intro')['show'] is True,'Another account gets its own introduction')
93
104
public_key=a.get('/api.php?action=push_config')['publicKey']
94
105
check(public_key==b.get('/api.php?action=push_config')['publicKey'],'Persistent server public key across sessions')
95
106
subscription={'endpoint':'https://fcm.googleapis.com/fcm/send/api-fixture','keys':{'p256dh':public_key,'auth':'AAAAAAAAAAAAAAAAAAAAAA'}}
@@ -90,6 +90,17 @@ with tempfile.TemporaryDirectory(prefix='api-', dir=ARTIFACTS) as tmp:90
check(json.loads(loaded)=={'base_url':'https://example.test','client_id':'fixture-client','client_secret':'fixture-secret'},'Empty fields use environment; configured fields take precedence')90
check(json.loads(loaded)=={'base_url':'https://example.test','client_id':'fixture-client','client_secret':'fixture-secret'},'Empty fields use environment; configured fields take precedence')91
b.state(); b.post('switch_user', user='test_user_2'); b.state()91
b.state(); b.post('switch_user', user='test_user_2'); b.state()92
check(b.state()['user']['name'] == 'test_user_2', 'Independent sessions')92
check(b.state()['user']['name'] == 'test_user_2', 'Independent sessions')93
check(a.state()['notificationIntroSeen'] is False,'New account has not seen notification introduction')94
csrf=a.csrf;a.csrf='wrong';a.post('claim_notification_intro',expected=403);a.csrf=csrf95
check(a.state()['notificationIntroSeen'] is False,'Invalid CSRF cannot consume introduction')96
same_user=Client();same_user.state()97
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:98
claims=list(executor.map(lambda client:client.post('claim_notification_intro'),[a,same_user]))99
check(sum(claim['show'] for claim in claims)==1,'Exactly one concurrent session claims the introduction')100
check(a.state()['notificationIntroSeen'] is True and same_user.state()['notificationIntroSeen'] is True,'Seen state persists across sessions')101
check(a.post('claim_notification_intro')['show'] is False,'Introduction cannot be shown again')102
check(b.state()['notificationIntroSeen'] is False,'Introduction state belongs to the account')103
check(b.post('claim_notification_intro')['show'] is True,'Another account gets its own introduction')93
public_key=a.get('/api.php?action=push_config')['publicKey']104
public_key=a.get('/api.php?action=push_config')['publicKey']94
check(public_key==b.get('/api.php?action=push_config')['publicKey'],'Persistent server public key across sessions')105
check(public_key==b.get('/api.php?action=push_config')['publicKey'],'Persistent server public key across sessions')95
subscription={'endpoint':'https://fcm.googleapis.com/fcm/send/api-fixture','keys':{'p256dh':public_key,'auth':'AAAAAAAAAAAAAAAAAAAAAA'}}106
subscription={'endpoint':'https://fcm.googleapis.com/fcm/send/api-fixture','keys':{'p256dh':public_key,'auth':'AAAAAAAAAAAAAAAAAAAAAA'}}