gitoria
All repositories: gitoria
16.5 KB
import { requiredPort } from './gate-ports.mjs';// tests/e2e-real.mjs — the gitoria walk in a REAL browser (an existing tab of lisbeth's test Chrome, over the CDP tunnel), not a gate:// prints numbers and writes screenshots. Own ident + gitoria on a throw-away store (ports from the env), the tab reaches them through// `ssh -R <port>:127.0.0.1:<port> lisbeth` as http://gitoria.localhost:<port> (*.localhost is loopback in Chrome, no resolver rule).// E2E_APP=<app dir> E2E_PORT=8742 E2E_IDENT_PORT=8743 E2E_TAG=old|new E2E_SHOTS=<dir> E2E_CDP=http://127.0.0.1:9223 E2E_TAB=<target id>// node tests/e2e-real.mjsimport { spawn, execFileSync } from 'node:child_process';import { rmSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { launchBrowser, Page } from './cdp.mjs';import { startIdent } from './identkit.mjs';const HERE = dirname(fileURLToPath(import.meta.url));const APP = resolve(process.env.E2E_APP || join(HERE, '..'));const PORT = requiredPort('E2E_PORT'), IPORT = requiredPort('E2E_IDENT_PORT');const TAG = process.env.E2E_TAG || 'x', SHOTS = process.env.E2E_SHOTS, TAB = process.env.E2E_TAB;const STORE = join(process.env.E2E_STORE, TAG);const BASE = `http://gitoria.localhost:${PORT}`, REPO = (s) => `http://${s}.gitoria.localhost:${PORT}`, IDENT_B = `http://ident.gitoria.localhost:${IPORT}`;const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || '/media/STORAGE/projects/WorldAPI/ident.worldapi.org';const MEASURE = readFileSync(join(HERE, 'mobile-measure.js'), 'utf8');const sleep = (ms) => new Promise(r => setTimeout(r, ms));const J = JSON.stringify;mkdirSync(SHOTS, { recursive: true }); rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });process.env.HL_CDP_URL = process.env.E2E_CDP || 'http://127.0.0.1:9223';let browserConn = null; let ident = null, server = null, page = null, slog = () => ''; const results = [];const noise = /ERR_|Failed to load resource|WebSocket connection/;const seen = new Set();const report = (where) => { for (const m of page.messages) { if ((m.level === 'error' || m.level === 'warning') && !noise.test(m.text) && !seen.has(m)) { seen.add(m); console.log('CONSOLE ERROR at', where, '|', m.text.split('\n')[0].slice(0, 160)); } } };const hydrated = () => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'hydrated', timeout: 30000 });const shows = (sel) => page.evaluate(`(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`);async function view(w) {if (w < 600) { await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: 844, deviceScaleFactor: 2, mobile: true }); await page.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 }); }else { await page.send('Emulation.setTouchEmulationEnabled', { enabled: false }); await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: 900, deviceScaleFactor: 1, mobile: false }); }await sleep(300);}async function shot(name) { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SHOTS, `${TAG}-${name}.png`), Buffer.from(data, 'base64')); }async function measure(name, w) {await hydrated(); await sleep(500);await page.evaluate(`window.__ev = []; document.addEventListener('pointerdown', e => window.__ev.push('pd:' + e.pointerType + ':' + e.target.tagName), true); document.addEventListener('click', e => window.__ev.push('click:' + e.target.tagName), true); 1`);const m = await page.evaluate(`window.__W = ${w};` + MEASURE);report(name + ' (after load)');const r = { name, w, scrollWidth: m.docScrollWidth, tapsSmall: m.tapsSmall, taps: m.taps, smallList: (m.tapsSmallList || []).slice(0, 6), inputsSmall: (m.inputsSmallList || []).length, header: m.headerH, boxesOver: (m.boxesOver || []).length };results.push(r); console.log(J(r)); await shot(name.replace(/[^a-z0-9]+/gi, '-'));}async function go(url, ready) {await page.goto(url); await page.send('Page.bringToFront'); await page.waitForSelector(ready, { timeout: 30000 }); }async function toggle(sel, box) {const open = `!!document.querySelector(${J(box)}) && document.querySelector(${J(box)}).matches(':popover-open')`;for (let i = 0; i < 4; i++) { // a real tap; when the page was re-rendering under it and nothing opened, tap again (a tap on an open box would close it, so only when closed)if (await page.evaluate(open)) break;await page.click(sel); await sleep(1500);if (i) console.log(' (tap', i + 1, 'for', box + ')');}report('tap ' + sel + ' (before it opened)');await page.waitFor(open, { label: box + ' open', timeout: 5000 }).catch(async (e) => { console.log('DIAG3', await page.evaluate(`(() => { const r = document.querySelector(${J(sel)}).getBoundingClientRect(); const e = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); return JSON.stringify({ r: [r.left, r.top, r.width, r.height], at: e && (e.tagName + '.' + (e.className.baseVal ?? e.className)), vis: document.visibilityState, focus: document.hasFocus(), ev: window.__ev }); })()`)); throw e; });await sleep(300); report('tap ' + sel + ' (after it opened)');}// mission 009 (theme 76f99f6): the main menu marks the current page beyond colour — aria-current="page" on exactly one visible link and an// inset accent bar (box-shadow). gitoria has ONE item (Repositories) and every page is under it (`current = true`), so "the marker moves"// is shown as: it is on every page, and it is still there after a REAL click on the item itself (to the home page).const marks = [];async function mark(name, w) {const sel = w < 600 ? '#sidebar main-menu a' : 'application-header main-menu a';const m = await page.evaluate(`(() => { const ls = [...document.querySelectorAll(${J(sel)})].filter(a => a.getBoundingClientRect().width > 0); const cur = ls.filter(a => a.getAttribute('aria-current') === 'page'); const c = cur[0]; const cs = c && getComputedStyle(c); return { links: ls.length, current: cur.length, text: c && c.textContent, cls: c && c.className, shadow: cs && cs.boxShadow, others: ls.filter(a => a.getAttribute('aria-current') !== 'page' && a.getAttribute('aria-current') !== 'false').length }; })()`);const ok = m.links === 1 && m.current === 1 && m.cls.includes('current') && !!m.shadow && m.shadow !== 'none';marks.push({ name, ok }); console.log(ok ? 'ok ' : 'FAIL', 'menu marker', name, J(m));return ok;}async function clickMenuItem(w, name) {const sel = w < 600 ? '#sidebar main-menu a' : 'application-header main-menu a';await page.click(sel); await page.waitForSelector('#repos li', { timeout: 30000 }); await hydrated();if (w < 600) { await toggle('button.menu-toggle', '#sidebar'); }await mark(name + ' (after a click on the item: home)', w);}async function walk(w, signedIn) {await view(w);const L = (n) => `${w} ${n}${signedIn ? '' : ' (signed out)'}`;await go(BASE + '/', '#repos li'); await measure(L('home'), w); if (w >= 600) await mark(L('home'), w);await go(REPO('alpha') + '/', '#reponame'); await measure(L('readme'), w); if (w >= 600) await mark(L('readme'), w);await go(REPO('alpha') + '/code', '#entries li'); await measure(L('code folder'), w); if (w >= 600) await mark(L('code folder'), w);await go(REPO('alpha') + '/code/src/a.txt', '#lines li'); await measure(L('file'), w); if (w >= 600) await mark(L('file'), w);await go(REPO('alpha') + '/commit/' + process.env.E2E_SHA, '#entries li'); await measure(L('commit'), w); if (w >= 600) await mark(L('commit'), w);await go(REPO('alpha') + '/pulls', 'repo-pulls'); await measure(L('pulls'), w); if (w >= 600) await mark(L('pulls'), w);if (signedIn) { await go(REPO('alpha') + '/settings', 'repo-settings'); await measure(L('settings'), w); }if (w < 600) {await go(REPO('alpha') + '/code', '#entries li'); await hydrated(); await toggle('button.menu-toggle', '#sidebar'); await measure(L('sidebar open'), w); await mark(L('code, sidebar open'), w); await shot('menu-' + w + '-code-sidebar'); await clickMenuItem(w, L('code'));if (signedIn) { await go(REPO('alpha') + '/', '#reponame'); await hydrated(); await toggle('button.user-toggle', '#user-menu'); await measure(L('user menu open'), w); }else { await go(REPO('alpha') + '/', '#reponame'); await hydrated(); await measure(L('login in the header'), w); }} else if (signedIn) {await go(REPO('alpha') + '/code', '#entries li'); await hydrated(); await clickMenuItem(w, L('code')); await shot('menu-' + w + '-home-after-click');await go(REPO('alpha') + '/', '#reponame'); await hydrated(); await toggle('button.user-toggle', '#user-menu'); await measure(L('user menu open'), w);}}try {ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IPORT });const alice = await ident.signIn('[email protected]');const APPKEY = await ident.registerApp(alice, 'gitoria (e2e)', [BASE]);server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],env: { ...process.env, GITORIA_PORT: String(PORT), GITORIA_STORAGE: join(STORE, 'mpackdb'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_WATCH: '0', GITORIA_GIT: join(STORE, 'git'),GITORIA_PUBLIC_URL: BASE, IDENT_URL: IDENT_B, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret } });let log = ''; slog = () => log; server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);for (let i = 0; i < 600; i++) { try { if ((await fetch(`http://127.0.0.1:${PORT}/api/repos`)).ok) break; } catch {} await sleep(250); }// the real tab: an EXISTING page target, attached (never created, never closed)const b = await launchBrowser(); browserConn = b.conn;const { sessionId } = await b.conn.send('Target.attachToTarget', { targetId: TAB, flatten: true });page = new Page(b, TAB, sessionId); await page._init();await b.conn.send('Target.activateTarget', { targetId: TAB }); // a background tab gets no real input: bring it to the front for the run, give the front back at the end{ const wf = page.waitFor.bind(page); page.waitFor = (e, o = {}) => wf(e, { ...o, timeout: (o.timeout || 10000) * 3 }); const gt = page.goto.bind(page); page.goto = (u, o = {}) => gt(u, { ...o, timeout: (o.timeout || 15000) * 3 }); }await view(1280);await page.send('Network.enable');// earlier runs leave cookies, a service worker and caches for these origins in the shared profile: clear exactly these origins, nothing elsefor (const o of [BASE, IDENT_B, REPO('alpha')]) await page.send('Storage.clearDataForOrigin', { origin: o, storageTypes: 'all' });for (const c of (await page.send('Network.getAllCookies')).cookies.filter(c => /gitoria\.localhost/.test(c.domain))) await page.send('Network.deleteCookies', { name: c.name, domain: c.domain, path: c.path });const [ck, cv] = alice.cookie.split('=');await page.send('Network.setCookie', { name: ck, value: cv, url: IDENT_B + '/' });// sign in by real clicks: login button (ident dropdown on a phone), choose the identity, give a nameawait view(390);await go(BASE + '/', '#repos, #heading'); await hydrated();await page.evaluate(`window.__t = []; document.querySelector('#ident-panel').addEventListener('toggle', e => window.__t.push(e.newState + '@' + Math.round(performance.now()))); document.addEventListener('pointerdown', e => window.__t.push('pd:' + e.pointerType + ':' + e.target.tagName + '@' + Math.round(performance.now())), true); document.addEventListener('click', e => window.__t.push('click:' + e.target.tagName + '@' + Math.round(performance.now())), true); 1`);if (!(await shows('#loginbutton'))) await page.click('button.ident-toggle');await page.waitFor(`(() => { const e = document.querySelector('#loginbutton'); return !!e && e.getBoundingClientRect().width > 0; })()`, { label: 'login button shown' }).catch(async (e) => { await page.click('button.ident-toggle'); await sleep(1500); console.log('after 2nd click open:', await page.evaluate(`document.querySelector('#ident-panel').matches(':popover-open')`), 'toggle rect', J(await page.evaluate(`(() => { const r = document.querySelector('button.ident-toggle').getBoundingClientRect(); const e = document.elementFromPoint(r.left + r.width/2, r.top + r.height/2); return [r.left, r.top, r.width, r.height, e && e.tagName + '.' + e.className, innerWidth, innerHeight, document.hasFocus()]; })()`))); console.log('EVENTS', J(await page.evaluate('window.__t'))); console.log('DIAG', await page.evaluate(`J = JSON.stringify; J({ href: location.href, tog: !!document.querySelector('button.ident-toggle'), panel: !!document.querySelector('#ident-panel'), open: document.querySelector('#ident-panel') && document.querySelector('#ident-panel').matches(':popover-open'), lb: !!document.querySelector('#loginbutton'), w: innerWidth, html: (document.querySelector('ident-menu')||{}).outerHTML })`), page.dumpConsole()); throw e; });await page.click('#loginbutton');await page.waitForSelector('#chooselist', { timeout: 30000 }); await hydrated(); await page.click('#chooselist li:nth-child(1) :is(a, button)');await page.waitForSelector('#nameform', { timeout: 30000 }); await hydrated(); await page.type('#displayname', 'alice'); await page.click('#namesave');await page.waitFor('!document.querySelector("#nameform")', { label: 'name saved' });await page.waitForSelector('#createform', { timeout: 30000 }); await hydrated();await page.type('#slug', 'alpha'); await page.type('#description', 'The first repository'); await page.click('#createsave');await page.waitFor('/Created .alpha./.test(document.body.innerText)', { label: 'repo alpha created', timeout: 30000 }).catch(async (e) => { console.log('DIAG2', await page.evaluate('location.href + " | " + document.body.innerText.slice(0, 600)'), page.dumpConsole().slice(-800)); throw e; });const work = join(STORE, 'work'); mkdirSync(work, { recursive: true });const git = (...a) => execFileSync('git', ['-C', work, '-c', 'user.name=t', '-c', '[email protected]', ...a], { stdio: 'pipe' }).toString();git('init', '-q', '-b', 'main'); mkdirSync(join(work, 'src'));writeFileSync(join(work, 'README.md'), '# Alpha project\n\nSome **strong** text with `code` and a [link](https://example.org/x).\n\n- one\n- two\n\n```\nlet x = 1 < 2\n```\n');writeFileSync(join(work, 'src/a.txt'), 'line one\nline two\n');git('add', '-A'); git('commit', '-q', '-m', 'first');writeFileSync(join(work, 'src/a.txt'), 'line one\nline two changed\nline three\n'); git('add', '-A'); git('commit', '-q', '-m', 'second');git('push', '-q', '-f', join(STORE, 'git', 'alpha.git'), 'main');const sha = git('rev-parse', 'HEAD').trim(); process.env.E2E_SHA = sha;console.log('tag', TAG, 'app', APP, 'sha', sha);await walk(390, true); await walk(1280, true);// signed out: drop the gitoria session cookieconst cks = (await page.send('Network.getAllCookies')).cookies.filter(c => /gitoria/.test(c.domain) || /^gitoriasid/.test(c.name));for (const c of cks) await page.send('Network.deleteCookies', { name: c.name, domain: c.domain, path: c.path });await walk(390, false);const bad = results.filter(r => (r.w < 600 && r.tapsSmall > 0) || r.scrollWidth > r.w || r.inputsSmall > 0 || r.boxesOver > 0);const desk = results.filter(r => r.w >= 600 && r.tapsSmall > 0).length; console.log('1280 audits with a target under 44 px (the theme is denser there on purpose):', desk);console.log(`SUMMARY ${TAG}: ${results.length} measurements, ${bad.length} with taps<44 / wider than screen / inputs<16 / boxes over`);for (const r of bad) console.log(' BAD', J(r));const mfail = marks.filter(m => !m.ok); console.log(`MENU MARKER ${TAG}: ${marks.length} checks, ${mfail.length} failed`); if (mfail.length) process.exitCode = 1;report('end'); console.log('console errors counted (tunnel network noise left out):', seen.size);writeFileSync(join(SHOTS, `${TAG}-results.json`), J(results, null, 1));await page.send('Emulation.clearDeviceMetricsOverride'); await page.send('Emulation.setTouchEmulationEnabled', { enabled: false });await page.goto('about:blank');} catch (e) { console.log('E2E ERROR', e.stack || e); console.log('SERVER LOG', slog().slice(-2500)); process.exitCode = 1; }finally {try { if (process.env.E2E_RESTORE && browserConn) await browserConn.send('Target.activateTarget', { targetId: process.env.E2E_RESTORE }); } catch {}try { server && server.kill('SIGTERM'); } catch {} try { ident && ident.stop && ident.stop(); } catch {}await sleep(500); process.exit(process.exitCode || 0);}
Branches
Latest commits
- fe209ffeMerge branch 'w56-owner-members' into mainGitoria
- fa0754c8|||PR repository owner transfer and members API (#55)mre
- 8862e537Merge branch 'w55-rename-org' into mainGitoria
- 014d2b7fOne immutable readers snapshot per move for the left-organization event (#53)mre
- 1859d506Decide who hears a repo left its organization by its readers before the move (#53)mre
- 499f25f2Review fixes for the Settings organization move (#53)mre
- ed3b922b|||PR move a repository into an organization in Settings (#53)mre
- 74ec2af8Merge branch 'w54-repo-rename-pr' into mainGitoria
- 9f7ce8d8Preserve rename compatibility and live page titlesmre
- c3d95b6e|||PR separate names and addresses, rename repositories in Settings (#53)mre
- ce08920dMerge branch 'w52c-header-phone' into mainGitoria
- 0bab9e46|||PR header: ident status wraps on phones instead of clippingmre
- e7af3eceMerge branch 'w52b-approval-followup' into mainGitoria
- c01e66c6|||PR approvals follow-up: live Merge after status writes, helpers (#52)mre
- 841da497Merge branch 'w53-pulls-speed-pr' into mainGitoria
- 80307ae2|||PR pulls page cache: live PR numbers, complete scans onlymre
- 69141f65|||PR pulls page: cache the git part per repo by branch tipsmre
- 155861f6Merge branch 'w52-person-approval' into mainGitoria
- b5435de8|||PR person approvals: second Kunibert round (#52)mre
- 3a8b2fb8|||PR person approvals: Kunibert review fixes (#52)mre