ident
All repositories: gitoria
21.2 KB
// tests/e2e-theme.mjs (ident mission 012): the theme move in a REAL browser (lisbeth's test Chrome over CDP, ONE existing tab reused,// never a new one), real mouse clicks and key events. Not a gate: prints numbers, writes screenshots.// node tests/e2e-theme.mjs <old|new> <port> <sink> <shotDir> <targetId> [cdpPort=8756]// ident runs on loreana on a COPY of the newest backup with a mail SINK file (never real mail), reached from lisbeth's Chrome through// `ssh -R <port>:127.0.0.1:<port>`. Per width (390, 1280): the signed-out pages, a real sign-in with the code read from the sink, the// 390 audit (tests/mobile-measure.js) of every page, then the walk: menus, sign out, register an app, an invite link, sign out everywhere.import { writeFileSync, readFileSync, existsSync } from 'node:fs';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';const [mode, port, sink, shotDir, tidArg, cdpPort = '8756'] = process.argv.slice(2); // tidArg: 'auto' = the first existing page tab, picked fresh from /json (never /json/new): an about:blank page, else a page of some worker's local test app (never a HyperConductor page)const BASE = `http://${process.env.E2E_HOST || '127.0.0.1'}:${port}`, sleep = ms => new Promise(r => setTimeout(r, ms)), J = JSON.stringify;const MEASURE = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'mobile-measure.js'), 'utf8');const EMAIL = '[email protected]'; // an account of the COPY (real data: apps, connections, notifications); the code goes to the sink fileconst list = await (await fetch(`http://127.0.0.1:${cdpPort}/json/list`)).json();const tgt = tidArg && tidArg !== 'auto' ? list.find(t => t.id === tidArg) : (list.find(t => t.type === 'page' && t.url === 'about:blank') || list.find(t => t.type === 'page' && /^http:\/\/(127\.0\.0\.1|[a-z.]*localhost)[:\/]/.test(t.url)));const tid = tgt.id;const ws = new WebSocket(tgt.webSocketDebuggerUrl.replace(/ws:\/\/[^/]+/, `ws://127.0.0.1:${cdpPort}`)); await new Promise(r => ws.onopen = r);let id = 0; const pend = new Map(), consoleErrors = [], dialogTexts = [];ws.onmessage = m => { const d = JSON.parse(m.data);if (d.id && pend.has(d.id)) { const [ok, bad] = pend.get(d.id); pend.delete(d.id); d.error ? bad(new Error(J(d.error))) : ok(d.result); }else if (d.method === 'Page.javascriptDialogOpening') { dialogTexts.push(d.params.message); send('Page.handleJavaScriptDialog', { accept: true }).catch(() => {}); } // the person presses OKelse if (d.method === 'Runtime.exceptionThrown') consoleErrors.push(J(d.params.exceptionDetails).slice(0, 200));else if (d.method === 'Runtime.consoleAPICalled' && d.params.type === 'error') consoleErrors.push(d.params.args.map(a => a.value || a.description).join(' ').slice(0, 200)); };const send = (method, params = {}) => new Promise((ok, bad) => { const i = ++id; pend.set(i, [ok, bad]); ws.send(J({ id: i, method, params })); });const ev = async x => { const r = await send('Runtime.evaluate', { expression: x, awaitPromise: true, returnByValue: true }); if (r.exceptionDetails) throw new Error(J(r.exceptionDetails).slice(0, 300)); return r.result.value; };const waitFor = async (x, label, t = 25000) => { for (const end = Date.now() + t; Date.now() < end;) { if (await ev(x).catch(() => false)) return true; await sleep(150); } console.log(' TIMEOUT', label); return false; };const rect = async sel => ev(`(() => { const e = document.querySelector(${J(sel)}); if (!e) return null; e.scrollIntoView({ block: 'center' }); const r = e.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2, w: r.width, h: r.height }; })()`);const click = async sel => { let r = await rect(sel); if (!r) throw new Error('no ' + sel); await sleep(120); r = await rect(sel); { const hit = await ev(`(() => { const t = document.querySelector(${J(sel)}); const h = document.elementFromPoint(${r.x}, ${r.y}); return t && h && (t === h || t.contains(h) || h.contains(t)) ? null : (h ? h.outerHTML.slice(0, 120) : 'nothing') + ' | vw=' + innerWidth + ' scrollY=' + scrollY; })()`).catch(() => null); if (hit) console.log(' CLICK COVERED', sel, hit); } for (const [type, extra] of [['mouseMoved', {}], ['mousePressed', { button: 'left', clickCount: 1 }], ['mouseReleased', { button: 'left', clickCount: 1 }]]) await send('Input.dispatchMouseEvent', { type, x: r.x, y: r.y, ...extra }); await sleep(150); const got = await ev('JSON.stringify(window.__got || [])').catch(() => '?'); if (got === '[]' || got === '?') console.log(' NO MOUSEDOWN reached the page after click on', sel, 'at', Math.round(r.x), Math.round(r.y), 'viewport', await ev('innerWidth + "x" + innerHeight + " dpr " + devicePixelRatio').catch(() => '?')); await ev('window.__got = []').catch(() => {}); };const key = async (k, code, vk) => { await send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: k, code, windowsVirtualKeyCode: vk }); await send('Input.dispatchKeyEvent', { type: 'keyUp', key: k, code, windowsVirtualKeyCode: vk }); };const typeInto = async (sel, text, clear = false) => { await click(sel); if (clear) { await send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'a', code: 'KeyA', windowsVirtualKeyCode: 65, modifiers: 2 }); await send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'a', code: 'KeyA', windowsVirtualKeyCode: 65, modifiers: 2 }); await key('Backspace', 'Backspace', 8); } for (const ch of text) { await send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch }); await send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch }); } };const shot = async name => { const r = await send('Page.captureScreenshot', { format: 'png' }); writeFileSync(`${shotDir}/${mode}-${name}.png`, Buffer.from(r.data, 'base64')); };const results = []; const check = (n, ok, d = '') => { results.push([n, !!ok]); console.log((ok ? 'PASS ' : 'FAIL ') + n + (ok ? '' : ' ' + d)); };const hydrated = () => waitFor(`!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1`, 'hydrated');const go = async (path, ready) => { await send('Page.navigate', { url: BASE + path }); await waitFor(`!!document.querySelector(${J(ready)})`, 'ready ' + ready + ' on ' + path); await hydrated(); await sleep(700); };const shows = sel => ev(`(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`);const txt = sel => ev(`(document.querySelector(${J(sel)}) || {}).textContent || ''`);const lastCode = (EM = EMAIL) => { const ls = existsSync(sink) ? readFileSync(sink, 'utf8').split('\n').filter(l => l.startsWith(EM + ' ')) : []; return ls.length ? ls.at(-1).split(' ')[1] : null; };const audits = [];async function audit(name, W) {const m = await ev(`window.__W = ${W};` + MEASURE);const r = { name, W, scrollWidth: m.docScrollWidth, taps: m.taps, tapsSmall: m.tapsSmall, small: m.tapsSmallList.slice(0, 6), inputsSmall: m.inputsSmall, inputsSmallList: m.inputsSmallList.slice(0, 4), textSmall: m.textSmall, textSmallList: m.textSmallList.slice(0, 4), wide: m.wide, wideList: m.wideList.slice(0, 3), header: m.headerH };audits.push(r); console.log('AUDIT', J(r)); await shot(`${W}-${name.replace(/[^a-z0-9]+/gi, '-')}`);}// THE SIGN-IN: email typed, "Send me a code" clicked, the code read from the sink like a person reads mail, typed, "Sign in" clickedasync function signIn(W, EM = EMAIL) {await go('/', '#emailform');await typeInto('#email', EM); const before = lastCode(EM);await click('#sendcode'); await waitFor(`location.pathname === '/code' && !!document.querySelector('#code')`, 'code page'); await hydrated();for (let i = 0; i < 160 && lastCode(EM) === before; i++) await sleep(250);const c = lastCode(EM); check(`${W}: the sink got a 6-digit code`, /^\d{6}$/.test(c || ''), String(c));if (W) await audit('code-page', W);await typeInto('#code', c); await ev('window.__m = 1'); await click('#verify'); // __m survives only WITHOUT a reload (mission 013)const ok = await waitFor(`!!document.querySelector('#meemail')`, 'signed in');await hydrated(); return ok;}await send('Page.enable'); await send('Runtime.enable'); await send('DOM.enable'); await send('Network.enable');await send('Target.activateTarget', { targetId: tid }).catch(() => {});await send('Page.bringToFront');await send('Page.addScriptToEvaluateOnNewDocument', { source: "window.__got = []; addEventListener('mousedown', e => window.__got.push((e.target.tagName || '') + '#' + (e.target.id || '') + '@' + Math.round(e.clientX) + ',' + Math.round(e.clientY)), true);" });await send('Storage.clearDataForOrigin', { origin: BASE, storageTypes: 'service_workers,cache_storage,local_storage' }).catch(() => {});await send('Network.deleteCookies', { name: 'identsid', url: BASE }).catch(() => {});const view = async W => { if (W === 390) { await send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true }); await send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 }); } else { await send('Emulation.setTouchEmulationEnabled', { enabled: false }); await send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false }); } await sleep(300); };const menuOpen = async (btn, pop) => { await click(btn); await waitFor(`document.querySelector(${J(pop)}).matches(':popover-open')`, pop + ' open'); await sleep(300); };const esc = async () => { await key('Escape', 'Escape', 27); await sleep(300); };try {for (const W of (process.env.WIDTHS || '390,1280').split(',').map(Number)) {await view(W); const T = `${W}-`;// ---- signed out -------------------------------------------------------------------------------------------------------await go('/', '#emailform'); await audit('signin', W);await go('/start', '#start'); await audit('start', W);await send('Page.navigate', { url: BASE + '/login?app=x&return=http://127.0.0.1:1/cb' }); await waitFor(`!!document.querySelector('#identerror')`, 'error page'); await sleep(400); await audit('login-error', W);await go('/apps', '#signinfirst'); await audit('apps-signed-out', W);// ---- the real sign-in --------------------------------------------------------------------------------------------------const ok = await signIn(W); check(`${T}sign-in with a code from the sink lands on the identities page`, ok && (await txt('#meemail')) === EMAIL, await txt('#meemail'));// the shell must show the signed-in header right after the IN-PLACE sign-in (no navigation, no reload since the click on "Sign in")if (mode === 'new') {await waitFor(`!!document.querySelector('application-header button.user-toggle')`, 'user menu after sign-in', 6000);check(`${T}right after the in-place sign-in (NO reload: the page marker is still there) the header has the user menu and the main menu`, await ev(`window.__m === 1 && !!document.querySelector('application-header button.user-toggle') && !!document.querySelector('application-header main-menu a[href="/apps"]')`));check(`${T}#whoami shows the address right after the sign-in`, (await txt('#whoami')) === EMAIL, await txt('#whoami'));await waitFor(`!!document.querySelector('main-menu a.current[href="/"]')`, 'current mark', 3000);check(`${T}IN PLACE right after the sign-in the main menu marks Identities (the MainMenu built late on the client gets the route, Hybriel web batch 4)`, await ev(`!!document.querySelector('main-menu a.current[href="/"]')`));await shot(`${T}signed-in-inplace`);}await sleep(500); await audit('identities', W);await click('#newidentity'); await waitFor(`!!document.querySelector('#identityform')`, 'form'); await sleep(400); await audit('identity-form', W);await click('#cancel'); await sleep(300);// SAVE an identity: the "Identity saved." notice (the stopgap reload had removed it)await click('#identities button[name=edit]'); await waitFor(`!!document.querySelector('#identityform')`, 'edit form'); await typeInto('#fnickname', `E2E${W}`, true); await ev('window.__m = 1'); await click('#saveidentity');await waitFor(`/Identity saved/.test((document.querySelector('#notice') || {}).textContent || '')`, 'saved notice', 8000);check(`${T}saving an identity shows the notice "Identity saved." (no reload)`, await ev(`window.__m === 1 && document.querySelector('#notice').textContent === 'Identity saved.' && !document.querySelector('#identityform')`), await txt('#notice')); await shot(`${T}identity-saved`);await go('/apps', '#appssection'); await audit('apps', W);await go('/inbox', '#inboxsection'); await audit('inbox', W);const cid = await ev(`(() => { const a = document.querySelector('#conns a'); return a ? a.getAttribute('href') : null; })()`);if (cid) { await go(cid, '#kindssection, #notfound'); await audit('app-settings', W); } else console.log(' (no connection in this copy)');// ---- menus (new shell only: the old header had three plain links) -------------------------------------------------------await go('/', '#identities');if (mode === 'new') {if (W === 390) {await menuOpen('button.menu-toggle', '#sidebar'); check(`${T}sidebar opens with the main menu ${J(await ev(`[...document.querySelectorAll('#sidebar main-menu a')].map(a => a.textContent)`))}`, (await ev(`document.querySelectorAll('#sidebar main-menu a').length`)) === 3); await shot(`${T}sidebar`);await click('#sidebar main-menu a[href="/apps"]'); await waitFor(`location.pathname === '/apps' && !!document.querySelector('#appssection')`, 'apps via sidebar'); await hydrated(); check(`${T}a tap on "Apps" in the sidebar opens /apps`, (await ev(`location.pathname`)) === '/apps');check(`${T}the sidebar menu marks Apps as current`, await ev(`!!document.querySelector('#sidebar main-menu a.current[href="/apps"]')`));} else {await click('application-header main-menu a[href="/inbox"]'); await waitFor(`location.pathname === '/inbox' && !!document.querySelector('#inboxsection')`, 'inbox via header'); await hydrated();check(`${T}the header's main menu opens /inbox`, (await ev(`location.pathname`)) === '/inbox');check(`${T}the header's main menu marks Inbox as current`, await ev(`!!document.querySelector('application-header main-menu a.current[href="/inbox"]')`));}await menuOpen('button.user-toggle', '#user-menu'); check(`${T}user menu opens: ${J(await txt('#whoami'))}, Sign out shown`, (await txt('#whoami')) === EMAIL && await shows('#menusignout')); await shot(`${T}user-menu`); await esc();check(`${T}Escape closes the user menu`, !(await ev(`document.querySelector('#user-menu').matches(':popover-open')`)));}// ---- register an app (real typing), its secret once, an invite for it -------------------------------------------------------await go('/apps', '#newapp'); await click('#newapp'); await waitFor(`!!document.querySelector('#appform')`, 'app form');const appName = `E2E ${mode} ${W}`;await typeInto('#fappname', appName); await typeInto('#forigins', `http://127.0.0.1:${port}`); await shot(`${T}app-form`); await click('#saveapp');await waitFor(`!!document.querySelector('#secret')`, 'secret shown'); const secret = await txt('#secret');check(`${T}app registered; the secret is shown once (${secret.slice(0, 3)}…)`, /^sk_[0-9a-f]{48}$/.test(secret)); await sleep(300); await audit('apps-secret', W);await click('#secretdone'); await sleep(300);const appKey = await ev(`(() => { const l = [...document.querySelectorAll('#apps li')].find(li => li.textContent.includes(${J(appName)})); const m = l && l.textContent.match(/pk_[0-9a-f]+/); return m ? m[0] : null; })()`);check(`${T}the app is listed with its key`, !!appKey, appKey);const inv = await (await fetch(`${BASE}/api/invites`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ key: appKey, secret, project: 'demo', role: 'member', return: `http://127.0.0.1:${port}/back` }) })).json();check(`${T}the app made an invite link`, !!inv.url, J(inv));if (inv.url) {const path = new URL(inv.url).pathname;await send('Page.navigate', { url: BASE + path }); await waitFor(`location.pathname.startsWith('/signin/') && !!document.querySelector('#apprequest')`, 'invite page'); await hydrated(); await sleep(500);check(`${T}the invite link opens the identity choice: ${J(await txt('#apprequest'))}`, (await txt('#apprequest')).includes('invited') && (await shows('#chooselist')) , await ev(`location.href`));await audit('invite-choose', W);}// ---- sign out (real click), sign in again, sign out everywhere ---------------------------------------------------------------await go('/', '#identities'); await ev('window.__m = 1'); await click('#signout'); if (!await waitFor(`!!document.querySelector('#emailform')`, 'signed out', 8000)) console.log(' DEBUG after #signout:', await ev(`location.href + ' | msg=' + document.querySelector('#message')?.textContent + ' | signout rect=' + JSON.stringify(document.querySelector('#signout')?.getBoundingClientRect()) + ' | top=' + document.elementFromPoint(window.innerWidth/2, 100)?.outerHTML.slice(0,100)`));check(`${T}"Sign out" returns to the sign-in form`, await shows('#emailform'));check(`${T}after "Sign out" (in place, NO reload) the header has NO user menu and no main menu`, await ev(`window.__m === 1 && !document.querySelector('application-header button.user-toggle') && !document.querySelector('application-header main-menu') && !document.querySelector('#code') && !!document.querySelector('#email')`)); await shot(`${T}signed-out`);if (!(await signIn(0))) throw new Error('second sign-in failed');if (mode === 'new') { await menuOpen('button.user-toggle', '#user-menu'); await click('#menusignout'); await waitFor(`location.pathname === '/' && !!document.querySelector('#emailform')`, 'user-menu sign out'); check(`${T}user menu "Sign out" signs out`, await shows('#emailform')); check(`${T}…and the header lost its user menu`, await ev(`!document.querySelector('application-header button.user-toggle')`)); if (!(await signIn(0))) throw new Error('third sign-in failed'); }await ev('window.__m = 1'); await click('#signoutall'); await waitFor(`!!document.querySelector('#emailform')`, 'signed out everywhere');check(`${T}"Sign out everywhere" (confirm accepted: ${J(dialogTexts.at(-1))}) returns to the sign-in form`, await shows('#emailform') && /every device/.test(dialogTexts.at(-1) || '')); await shot(`${T}signed-out-all`);check(`${T}after "Sign out everywhere" (in place, NO reload): notice "Signed out on every device." and the header has NO user menu`, await ev(`window.__m === 1 && document.querySelector('#notice').textContent === 'Signed out on every device.' && !document.querySelector('application-header button.user-toggle') && !document.querySelector('#code')`), await txt('#notice'));// ---- the FIRST LOGIN (a new address on the copy): the welcome form stays in place, Skip ends it with a reload, then the header has its user menuif (mode === 'new') {const NEWADDR = `e2e-welcome-${W}-${Date.now() % 100000}@example.test`;if (await signIn(0, NEWADDR)) {check(`${T}first login: the welcome form is shown (optional names, Skip)`, await ev(`!!document.querySelector('#welcome') && !!document.querySelector('#skip')`)); await shot(`${T}welcome`);check(`${T}first login, in place: the header already has the user menu (${NEWADDR})`, await ev(`window.__m === 1 && !!document.querySelector('application-header button.user-toggle')`));await click('#skip'); await waitFor(`!document.querySelector('#identityform')`, 'welcome skipped', 8000);check(`${T}Skip closes the welcome in place and the header has the user menu (${NEWADDR})`, await ev(`!document.querySelector('#identityform') && !!document.querySelector('application-header button.user-toggle')`) && (await txt('#whoami')) === NEWADDR, await txt('#whoami'));await shot(`${T}welcome-done`);} else check(`${T}first login signs in`, false);await send('Network.deleteCookies', { name: 'identsid', url: BASE }); // the next width starts signed out}}const badAudits = audits.filter(a => (a.W === 390 && a.tapsSmall) || a.wide || a.scrollWidth > a.W || a.inputsSmall);const s = (f) => audits.filter(f).reduce((n, a) => n + a.tapsSmall, 0);console.log(`\nSUMMARY ${mode}: audits ${audits.length}, at 390 taps<44 total ${s(a => a.W === 390)}, wider-than-screen ${audits.filter(a => a.W === 390).reduce((n, a) => n + a.wide, 0)}, inputs<16 ${audits.filter(a => a.W === 390).reduce((n, a) => n + a.inputsSmall, 0)}, text<14 ${audits.filter(a => a.W === 390).reduce((n, a) => n + a.textSmall, 0)}; checks ${results.filter(r => r[1]).length}/${results.length}; console errors ${consoleErrors.length}`);for (const e of consoleErrors.slice(0, 6)) console.log(' CONSOLE', e);writeFileSync(`${shotDir}/${mode}-audits.json`, J(audits, null, 1));} catch (e) { console.log('E2E ERROR', e.stack || e); console.log(' PAGE:', await ev(`location.href + ' :: ' + document.body.innerText.slice(0, 300)`).catch(() => '?')); process.exitCode = 1; }await send('Emulation.clearDeviceMetricsOverride'); await send('Emulation.setTouchEmulationEnabled', { enabled: false });await send('Network.deleteCookies', { name: 'identsid', url: BASE }).catch(() => {});await send('Page.navigate', { url: 'about:blank' }); await sleep(300);ws.close(); process.exit(process.exitCode || 0);
Branches
Latest commits
- 0f6d1592Merge branch 'f18b-shell-session' into mainIdent
- 19868218|||PR ident#39 shell reads its session member instead of a cross-file emitmre
- 5d1b3fedMerge branch 'v61-day61' into mainIdent
- 83faeb15|||PR ident: vendor Hybriel day61mre
- b2572b34Merge branch 'v59-day59' into mainIdent
- 67cf016d|||PR ident: vendor Hybriel day59mre
- 600c043dMerge branch 'v58-day58' into mainIdent
- 365f8c80|||PR ident: vendor Hybriel day58mre
- 585126e5Merge branch 'f16-setf' into mainIdent
- 953bf03a|||PR ident setF mirror dropped (hybriel#370)mre
- a1419d9cMerge branch 'f15-navigate' into mainIdent
- 3b3e451f|||PR ident#36 navigate to the app instead of location.assignmre
- e36f4516Merge branch 'f14-online' into mainIdent
- 2c5eac91|||PR ident#38 online state without probe timermre
- bf1980f2Merge branch 'v56-day56' into mainIdent
- 62ae0adf|||PR ident: vendor Hybriel day56mre
- 0d18abc4Merge branch 'f13-avatar' into mainIdent
- 2a99730a|||PR ident#37 avatar in hlmre
- fa4ed25bMerge branch 'f11-upsert' into mainIdent
- 8f3d9bc9|||PR ident#42 keyed upsert and removemre