calendar
All repositories: gitoria
20.0 KB
// tests/notify-paths.mjs — calendar#9 (mission 003): WHERE A REMINDER FIRES. Real headless Chrome as a phone (390 px,// touch, Android Chrome user agent), own ident (tests/identkit.mjs, a copy without .env), own server + storage.// node tests/notify-paths.mjs [app dir] (default: this tree; give an old tree to see the old behaviour)// env: NOTIFY_GATE_PORT (app, default 8700; ident = +1; Chrome = +2…+9), NOTIFY_GATE_SCRATCH (where the stores, Chrome// profiles and screenshots go; default <app>/.scratch/notify-gate).// Each scenario has its own identity and its own Chrome, so a tab can only ever show ITS user's reminder:// permission — no permission yet: is "Turn on notifications" offered, does a real tap ask the browser?// open — the app opened and left open, NOT touched (the phone on the table): does the reminder come?// touched — the app open and touched once: does it come on time?// resume — touched, then the phone switches away (Chrome FREEZES the tab, as Android does), back after the reminder time// discarded — touched, frozen past the reminder time, and Android dropped the tab: coming back loads the app fresh// closed — touched, then the tab is closed (the browser and its service worker stay): does anything fire?// Every reminder is "1 minute before" an event 2–3 minutes ahead. What a tab showed is read from the service worker's// notifications (registration.getNotifications) and from a recorder around showNotification / new Notification.import { spawn } from 'node:child_process';import { writeFileSync, existsSync, mkdirSync, rmSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';const HERE = dirname(fileURLToPath(import.meta.url));const APP = resolve(process.argv[2] || resolve(HERE, '..'));const PORT = Number(process.env.NOTIFY_GATE_PORT || 8700);const BASE = `http://127.0.0.1:${PORT}`;const SCRATCH = resolve(process.env.NOTIFY_GATE_SCRATCH || join(APP, '.scratch', 'notify-gate'));rmSync(SCRATCH, { recursive: true, force: true });mkdirSync(join(SCRATCH, 'chrome'), { recursive: true });process.env.TMPDIR = join(SCRATCH, 'chrome'); // cdp.mjs makes the Chrome profiles under the temp dirif (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';const { launchBrowser } = await import('./cdp.mjs');const { startIdent } = await import('./identkit.mjs');const IDENT_DIR = process.env.CALENDAR_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));const ONLY = (process.env.NOTIFY_GATE_ONLY || '').split(',').filter(Boolean);const sleep = (ms) => new Promise(r => setTimeout(r, ms));const J = JSON.stringify;const pad = (n) => String(n).padStart(2, '0');let failures = 0, passes = 0, gaps = 0;const results = {};function check(label, ok, detail = '') {console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);if (ok) passes++; else failures++;}// what needs a piece Hybriel does not have yet (report 003): printed as GAP, not counted — NOTIFY_GATE_STRICT=1 counts itfunction gap(label, ok, detail = '') {if (ok || process.env.NOTIFY_GATE_STRICT) return check(label, ok, detail);console.log(`GAP ${label} — ${detail}`);gaps++;}const stamp = () => new Date().toTimeString().slice(0, 8);const say = (who, what) => console.log(`${stamp()} [${who}] ${what}`);// the recorder: every notification a page shows, with the time (also the ones a constructor would refuse on Android)const RECORDER = `(() => {window.__notes = [];window.__asked = [];const R = globalThis.ServiceWorkerRegistration;if (R && R.prototype.showNotification) { const o = R.prototype.showNotification; R.prototype.showNotification = function (t, x) { window.__notes.push({ via: 'worker', title: t, body: x && x.body, at: Date.now() }); return o.call(this, t, x); }; }const N = window.Notification;if (N) {const W = function (t, x) { window.__notes.push({ via: 'new Notification', title: t, body: x && x.body, at: Date.now() }); return new N(t, x); };W.prototype = N.prototype;Object.defineProperty(W, 'permission', { get: () => N.permission });W.requestPermission = (...a) => { window.__asked.push({ at: Date.now(), active: !!(navigator.userActivation && navigator.userActivation.isActive) }); return N.requestPermission(...a); };window.Notification = W;}})();`;const ANDROID_UA = 'Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Mobile Safari/537.36';let ident = null, server = null, log = '';const browsers = [];async function stopAll() {for (const b of browsers) { try { await b.close(); } catch {} }if (ident) { try { await ident.stop(); } catch {} ident = null; }if (server) {try { server.kill('SIGTERM'); } catch {}await new Promise(r => { if (server.exitCode !== null || server.signalCode !== null) return r(); server.once('exit', r); setTimeout(r, 3000); });server = null;}}async function phone(port) {const browser = await launchBrowser({ debugPortRange: [port, port] });browsers.push(browser);return { browser, page: await tab(browser) };}// a tab dressed as the phone's browserasync function tab(browser) {const page = await browser.newPage();await page.addInitScript(RECORDER);await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 2, mobile: true });await page.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });await page.send('Emulation.setUserAgentOverride', { userAgent: ANDROID_UA, platform: 'Linux armv8l' });return page;}const hydrated = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 120000, label: 'hydrated' });async function tap(page, sel) {const at = await page.evaluate(`(() => { const e = document.querySelector(${J(sel)}); if (!e) return null; e.scrollIntoView({ block: 'center' }); const r = e.getBoundingClientRect(); return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }; })()`);if (!at) throw new Error('tap: no ' + sel);await page.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: at.x, y: at.y }] });await page.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });}const shownBy = (page) => page.evaluate(`navigator.serviceWorker.getRegistration().then(r => r ? r.getNotifications() : []).then(l => l.map(n => n.title + '|' + n.body))`);const recorded = (page) => page.evaluate('window.__notes || []');const planned = (page) => page.evaluate(`(document.querySelector('#notify-planned') || {}).textContent || ''`);const shot = async (page, name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `${name}.png`), Buffer.from(data, 'base64')); };// a signed-in phone of `who` with permission given (as after "Allow"), and its event `title`: start 2–3 min ahead,// own reminder 1 minute before. Returns the reminder's instant.async function setUp(name, who, port, { grant = true } = {}) {const { page } = await phone(port);if (grant) await page.send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] });const code = await ident.selectorCode(who, APPKEY, BASE);await page.goto(BASE + '/login/callback?ident_code=' + code, { timeout: 120000 });await page.waitForSelector('#logout', { timeout: 60000 });await hydrated(page);await page.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { label: 'service worker active', timeout: 60000 });return page;}async function addEvent(page, title) {const zone = await page.evaluate('Intl.DateTimeFormat().resolvedOptions().timeZone');const now = Date.now();const start = new Date(Math.ceil((now + 150000) / 60000) * 60000); // a whole minute, ≥ 2.5 min aheadconst remindAt = start.getTime() - 60000;const dateOf = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;const cookie = (await page.cookies([BASE])).map(c => c.name + '=' + c.value).join('; ');const win = [dateOf(new Date(now - 86400000 * 3)), dateOf(new Date(now + 86400000 * 9))];const fields = { title, allDay: false, startDate: dateOf(start), startTime: `${pad(start.getHours())}:${pad(start.getMinutes())}`, endDate: '', endTime: '', place: '', notes: '', zone, custom: true, reminders: [{ unit: 'minutes', n: '1', time: '09:00' }] };const r = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', cookie }, body: J({ t: 'emit', i: 1, event: 'calSave', payload: [fields, win[0], win[1]] }) });const j = JSON.parse(await r.text());if (!j.value || j.value.error) throw new Error('calSave: ' + r.status + ' ' + J(j));return remindAt;}const until = async (t) => { const w = t - Date.now(); if (w > 0) await sleep(w); };const seen = (list, title) => list.some(g => g.startsWith(title + '|'));const recSeen = (list, title) => list.find(n => n.title === title);const late = (n, at) => n ? Math.round((n.at - at) / 1000) + ' s after the reminder time' : 'not shown';let APPKEY = null;const scenarios = {// ---- no permission yet: the button and the browser's question ----async permission(who, port) {const page = await setUp('permission', who, port, { grant: false });const before = await page.evaluate(`({ ask: !document.querySelector('#notify-ask').classList.contains('hidden'), permission: Notification.permission })`);await shot(page, 'permission-1-loaded');await tap(page, '#month-title');await sleep(1500);const afterTouch = await page.evaluate(`!document.querySelector('#notify-ask').classList.contains('hidden')`);let asked = [];// the controls live in the reminder settings (C13): user menu → "Reminder settings" → the notifications sectionif (afterTouch) { await tap(page, '#settings-open'); await sleep(1200); await tap(page, '#notify-ask'); await sleep(2000); asked = await page.evaluate('window.__asked'); }await shot(page, 'permission-2-touched');results.permission = { before, afterTouch, asked };say('permission', J(results.permission));gap('permission: "Turn on notifications" is offered as soon as the page shows (no touch needed; Hybriel: no hook when a page is shown)', before.ask === true, 'button hidden until the first touch: ' + J(before));check('permission: a real tap on it asks the browser, while the tap still counts as a user gesture', asked.length > 0 && asked[0].active, J({ afterTouch, asked }));},// ---- the app open and left alone ----async open(who, port) {const page = await setUp('open', who, port);const at = await addEvent(page, 'Open untouched');await page.goto(BASE + '/', { timeout: 120000 });await hydrated(page);await sleep(3000);const p0 = await planned(page);say('open', `loaded, not touched; planned text "${p0}"; reminder at ${new Date(at).toTimeString().slice(0, 8)}`);await until(at + 25000);const rec = await recorded(page), sw = await shownBy(page);await shot(page, 'open-untouched');results.open = { planned: p0, recorded: rec, shown: sw, at };gap('open (not touched): the reminder comes on time (Hybriel: no hook when a page is shown)', !!recSeen(rec, 'Open untouched') && seen(sw, 'Open untouched') && recSeen(rec, 'Open untouched').at - at < 20000, J({ planned: p0, shown: sw, rec }));},// ---- open and touched once ----async touched(who, port) {const page = await setUp('touched', who, port);const at = await addEvent(page, 'Open touched');await page.goto(BASE + '/', { timeout: 120000 });await hydrated(page);await tap(page, '#month-title');await page.waitFor(`document.querySelector('#notify-planned').textContent.length > 0`, { timeout: 20000, label: 'planned' }).catch(() => {});const p0 = await planned(page);say('touched', `touched; planned "${p0}"`);await until(at + 25000);const rec = await recorded(page), sw = await shownBy(page);results.touched = { planned: p0, recorded: rec, shown: sw, at };check('open (touched once): the reminder comes on time, through the service worker', !!recSeen(rec, 'Open touched') && recSeen(rec, 'Open touched').via === 'worker' && seen(sw, 'Open touched') && recSeen(rec, 'Open touched').at - at < 20000, J({ planned: p0, shown: sw, rec }));// loaded again before the event starts: what was shown is not shown a second timeawait page.goto(BASE + '/', { timeout: 120000 });await hydrated(page);await tap(page, '#month-title');await sleep(5000);const again = await recorded(page);check('open (touched once): loaded again, a reminder already shown is not shown twice', !recSeen(again, 'Open touched'), J(again));},// ---- switched away (frozen), back later in the same tab ----async resume(who, port) {const page = await setUp('resume', who, port);const at = await addEvent(page, 'Back later');await page.goto(BASE + '/', { timeout: 120000 });await hydrated(page);await tap(page, '#month-title');await page.waitFor(`document.querySelector('#notify-planned').textContent.length > 0`, { timeout: 20000, label: 'planned' }).catch(() => {});say('resume', `touched; planned "${await planned(page)}"; now frozen (switched away)`);await page.send('Page.setWebLifecycleState', { state: 'frozen' });await until(at + 30000);await page.send('Page.setWebLifecycleState', { state: 'active' });say('resume', 'back (active)');await sleep(15000);const rec = await recorded(page), sw = await shownBy(page);results.resume = { recorded: rec, shown: sw, at };const n = recSeen(rec, 'Back later');say('resume', 'notification: ' + late(n, at));check('switched away: the reminder is shown at the latest when the app is back', !!n && seen(sw, 'Back later'), J({ shown: sw, rec }));check('switched away: shown once', rec.filter(x => x.title === 'Back later').length === 1 || sw.filter(g => g.startsWith('Back later|')).length === 1, J(rec));},// ---- switched away, the tab dropped by Android: back = a fresh load ----async discarded(who, port) {const page = await setUp('discarded', who, port);const at = await addEvent(page, 'Tab dropped');await page.goto(BASE + '/', { timeout: 120000 });await hydrated(page);await tap(page, '#month-title');await page.waitFor(`document.querySelector('#notify-planned').textContent.length > 0`, { timeout: 20000, label: 'planned' }).catch(() => {});say('discarded', `touched; planned "${await planned(page)}"; frozen, then dropped`);await page.send('Page.setWebLifecycleState', { state: 'frozen' });await until(at + 30000);// Android dropped the frozen tab; coming back loads the app as a fresh documentconst browser = browsers.find(b => b.pages.includes(page));await page.close();browser.pages = browser.pages.filter(p => p !== page);const back = await tab(browser);await back.send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] }); // a CDP grant ends with its tab; a real one staysawait back.goto(BASE + '/', { timeout: 120000 });await hydrated(back);await tap(back, '#month-title');await sleep(15000);const rec = await recorded(back), sw = await shownBy(back);await shot(back, 'discarded-back');if (process.env.NOTIFY_GATE_DEBUG) console.log('[discarded] console:\n' + back.dumpConsole() + '\nlocalStorage ' + J(await back.evaluate('JSON.stringify(localStorage)')) + ' permission ' + await back.evaluate('Notification.permission'));results.discarded = { recorded: rec, shown: sw, at };say('discarded', 'notification: ' + J(sw));check('tab dropped while away: coming back shows the missed reminder, saying when the event starts', sw.some(g => /^Tab dropped\|Starts at \d\d:\d\d$/.test(g)), J({ shown: sw, rec }));},// ---- the tab closed; the browser and the worker stay ----async closed(who, port) {const page = await setUp('closed', who, port);const at = await addEvent(page, 'App closed');await page.goto(BASE + '/', { timeout: 120000 });await hydrated(page);await tap(page, '#month-title');await page.waitFor(`document.querySelector('#notify-planned').textContent.length > 0`, { timeout: 20000, label: 'planned' }).catch(() => {});say('closed', `touched; planned "${await planned(page)}"; closing the tab`);const browser = browsers.find(b => b.pages.includes(page));await page.close();browser.pages = browser.pages.filter(p => p !== page);await until(at + 25000);// a same-origin page that is NOT the app (an icon) reads what the worker showsconst look = await browser.newPage();await look.goto(BASE + '/icons/icon-192.png', { timeout: 60000 });const sw = await shownBy(look);results.closed = { shown: sw, at };say('closed', 'shown: ' + J(sw));gap('closed app: the reminder comes on time (needs Web Push: Hybriel has no VAPID/ECDH/AES-GCM and no worker push listener)', seen(sw, 'App closed'), J(sw));// opened again before the event starts: the missed reminder shows at onceawait look.close();browser.pages = browser.pages.filter(p => p !== look);const back = await tab(browser);await back.send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] }); // a CDP grant ends with its tab; a real one staysawait back.goto(BASE + '/', { timeout: 120000 });await hydrated(back);await tap(back, '#month-title');await sleep(10000);const sw2 = await shownBy(back), rec2 = await recorded(back);await shot(back, 'closed-reopened');say('closed', 'reopened: ' + J(sw2));results.closedReopened = { shown: sw2, recorded: rec2, reopenedAfter: Math.round((Date.now() - at) / 1000) };check('closed app, opened again before the event: the missed reminder shows at once', sw2.some(g => /^App closed\|Starts at \d\d:\d\d$/.test(g)) && !!recSeen(rec2, 'App closed'), J({ sw2, rec2 }));},};async function main() {mkdirSync(join(SCRATCH, 'store'), { recursive: true });ident = await startIdent({ identDir: IDENT_DIR, workDir: join(SCRATCH, 'store', 'ident'), port: PORT + 1 });const names = Object.keys(scenarios).filter(n => !ONLY.length || ONLY.includes(n));const who = {};for (const n of names) who[n] = await ident.signIn(n + '@example.org');APPKEY = await ident.registerApp(who[names[0]], 'calendar (notify gate)', [BASE]);server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, env: { ...process.env, CALENDAR_PORT: String(PORT), HL_HOST: '127.0.0.1', CALENDAR_SESSIONS: join(SCRATCH, 'store', 'sessions') + '/',CALENDAR_STORAGE: join(SCRATCH, 'store', 'mpackdb'), CALENDAR_WATCH: '0', CALENDAR_PUBLIC_URL: BASE, IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base,IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret }, stdio: ['ignore', 'pipe', 'pipe'] });server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);mkdirSync(join(SCRATCH, 'store', 'sessions'), { recursive: true });for (let i = 0; ; i++) { // a cold compile takes up to 41 s: wait up to 150 stry { if ((await fetch(BASE + '/')).ok) break; } catch {}if (i > 600) throw new Error('server did not come up\n' + log);await sleep(250);}say('gate', `app ${APP} up; scenarios ${names.join(' ')}`);// all scenarios at once, each in its own Chrome (ports PORT+2 …)const runs = names.map((n, i) => scenarios[n](who[n], PORT + 2 + i).catch(e => check(n + ' ran', false, String(e && e.stack || e))));await Promise.all(runs);}try { await main(); } catch (e) { check('gate ran', false, String(e && e.stack || e)); }writeFileSync(join(SCRATCH, 'results.json'), J(results, null, 1));if (failures) console.log('---- server log (tail)\n' + log.slice(-2000));await stopAll();console.log(`${passes} passed, ${failures} failed, ${gaps} Hybriel gaps (app ${APP})`);process.exit(failures ? 1 : 0);
Branches
Latest commits
- b37cc1da|||PR Vendor Hybriel day59Atlas
- 05665102Merge branch 'vendor-day56' into mainAtlas
- 687296fb|||PR Vendor Hybriel day56Atlas
- a6166d4eMerge branch 'hl-standard-3' into mainAtlas
- 6d0eb3b0|||PR Calendar day add buttons only when signed in (Kunibert minor)Atlas
- add4b499|||PR Make calendar day actions keyboard accessibleAtlas
- 79e49b4dMerge branch 'hl-standard' into mainAtlas
- e9fec7bb|||PR HL-STANDARD clean-up: typed parameters, plain locals, by-reference cacheAtlas
- eff166a4Re-vendor complete Hybriel plugins and runtime to day44mre
- cef81394Wait for the DST fixture page instead of an unused socketmre
- 42434f47Check lazy-session cookies after login with a stored anonymous fixturemre
- 728e84e3Re-vendor complete Hybriel day41 plugin directoriesmre
- cbd7ff43Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
- 59d1da0acalendar: plain declarations instead of needless let in 9 files (calendar#17): 49 declarations that are never reassigned; reassigned ones and the timer closure's p stay letmre
- f5415cf9calendar: the Style blocks in the language's nested form (calendar#16): rules named after the View's own elements with their children nested, pseudo-classes and @media nested, merged duplicate select rule; same CSS, shots identical in Chrome at 4 sizesmre
- edb7c947calendar: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 56+4 failing → 60 passedmre
- bf8cc0fcStyles move into their components: the shell's styles into main.hl, the events and the editors into the month view's Style block; styles.hl keeps only the theme inherit, the accent and the message line; .gitignore ignores a bin symlink too; tests/styles-shots.mjs for the before/after pixel comparemre
- 5d8579d7README: login.js stays by caramboleyo's explicit rulemre
- cc759328Merge sb3-standby: calendar deploys through its standbymre
- f2fcdc6dcalendar: a standby container (port 45015, profile standby, reminder clock off) and a /health page; deploy hands over through standby-swap.sh without a gapmre