gitoria
All repositories: gitoria
15.0 KB
import { requiredPort, requiredPortRange } from './gate-ports.mjs';// tests/chain.mjs — gitoria#22: WHAT A TAB CLICK REPLACES, MEASURED IN A REAL CHROME WITH REAL CLICKS (C2's method).// Own ident + gitoria on a copy of the data (localhost hosts: alpha.localhost resolves to 127.0.0.1 in Chrome itself). Seeds repos// `alpha` (README, code, a branch, a pull request), `longdoc` (a 2 003-line README) and `gamma` (empty) through the real UI.// Then, in the measuring browser, per viewport: Readme → Code → Pulls → Readme → Code on alpha with real clicks, a// MutationObserver counting the elements REMOVED / ADDED by each click, and the repo head, the tab nav and the page elements tagged with// a property BEFORE the click — after the click they must still be the SAME node objects (standing levels). Then the// README timing on `longdoc` (click Code → click Readme: click → README text in the DOM, long-task time, page-side).// Results: .scratch/chain-<label>.json + a table on stdout. Screenshots .scratch/chain-<label>-<viewport>-<step>.png.// CHAIN_SERVE=1 only seed + serve (prints READY, runs until SIGTERM) — start it OUTSIDE the lisbeth lock; CHAIN_MEASURE=1 only measure an// already serving app on CHAIN_PORT (the E2E part that goes under the lock).// CHAIN_APP=<app dir> the code under test (default: this app); CHAIN_LABEL=old|new; CHAIN_PORT=8720 CHAIN_IDENT_PORT=8721// CHAIN_CDP=http://127.0.0.1:9223 measure in lisbeth's Chrome (a reverse tunnel for CHAIN_PORT must exist; ONE tab is reused, nothing is// closed) — run it under `flock …/lisbeth.lock`. Without it a headless Chrome is launched.import { spawn, execFileSync } from 'node:child_process';import { rmSync, mkdirSync, writeFileSync, existsSync } 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';if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';const HERE = dirname(fileURLToPath(import.meta.url));const OWN = resolve(HERE, '..');const APP = resolve(process.env.CHAIN_APP || OWN);const LABEL = process.env.CHAIN_LABEL || 'run';const PORT = requiredPort('CHAIN_PORT');const IDENT_PORT = requiredPort('CHAIN_IDENT_PORT');const CHROME_PORTS = requiredPortRange('CHAIN_CHROME');const BASE = `http://localhost:${PORT}`;const REPO = (s) => `http://${s}.localhost:${PORT}`;const IDENT_B = `http://localhost:${IDENT_PORT}`;const SCRATCH = join(OWN, '.scratch');const STORE = join(SCRATCH, 'chain-store-' + LABEL);const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || '/media/STORAGE/projects/WorldAPI/ident.worldapi.org';const sleep = (ms) => new Promise(r => setTimeout(r, ms));const J = JSON.stringify;mkdirSync(SCRATCH, { recursive: true });let server = null, ident = null, log = '';const out = { label: LABEL, app: APP, steps: [], timing: [] };function startServer(env) {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, 'db'), 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, ...env } });server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);}async function serverUp() {for (let i = 0; i < 960; i++) { try { if ((await fetch(`http://127.0.0.1:${PORT}/api/repos`)).ok) return; } catch {} await sleep(250); }throw new Error('gitoria did not come up\n' + log);}const hydrated = (p) => p.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'hydrated', timeout: 60000 });const shot = async (p, name) => { const { data } = await p.send('Page.captureScreenshot', { format: 'png' }); const f = join(SCRATCH, `chain-${LABEL}-${name}.png`); writeFileSync(f, Buffer.from(data, 'base64')); return f; };async function seed() {const b = await launchBrowser({ debugPortRange: CHROME_PORTS });const A = await b.newPage();try {await A.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });await A.goto(IDENT_B + '/'); await A.waitForSelector('#email'); await hydrated(A);await A.type('#email', '[email protected]'); await A.click('#sendcode');await A.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'ident code page' }); await hydrated(A);await A.type('#code', ident.lastCode('[email protected]')); await A.click('#verify'); await A.waitForSelector('#signout, #menusignout', { timeout: 15000 });await A.goto(BASE + '/'); await A.waitForSelector('#loginbutton'); await hydrated(A);await A.click('#loginbutton'); await A.waitForSelector('#chooselist', { timeout: 15000 }); await hydrated(A); await A.click('#chooselist li:nth-child(1) :is(a, button)');await A.waitFor(`location.href === ${J(BASE + '/')} && !!document.querySelector("#nameform")`, { label: 'name prompt' }); await hydrated(A);await A.type('#displayname', 'alice'); await A.click('#namesave'); await A.waitFor('!document.querySelector("#nameform")'); await A.waitForSelector('#createform');for (const slug of ['alpha', 'longdoc', 'gamma']) {for (let attempt = 1; ; attempt++) { // a loaded machine drops a click now and then: look, then retryawait A.evaluate('document.querySelector("#slug").value = ""; document.querySelector("#description").value = ""');await A.type('#slug', slug); await A.type('#description', 'repo ' + slug); await A.click('#createsave');try { await A.waitFor(`[...document.querySelectorAll('#repos .repo-slug')].some(a => a.textContent === ${J(slug)})`, { label: 'created ' + slug, timeout: 30000 }); break; }catch (e) { if (attempt >= 3) throw e; }}}} finally { await b.close(); }const push = (slug, files, extra = () => {}) => {const work = join(STORE, 'work-' + slug); rmSync(work, { recursive: true, force: true }); mkdirSync(work, { recursive: true });const git = (...a) => execFileSync('git', ['-C', work, '-c', 'user.name=t', '-c', '[email protected]', ...a], { stdio: 'pipe' });git('init', '-q', '-b', 'main');for (const [p, c] of Object.entries(files)) { mkdirSync(dirname(join(work, p)), { recursive: true }); writeFileSync(join(work, p), c); }git('add', '-A'); git('commit', '-q', '-m', 'files'); extra(git, work);git('push', '-q', '-f', join(STORE, 'git', slug + '.git'), '--all');};push('alpha', { 'README.md': '# Alpha\n\nSome **text** and a list:\n\n- one\n- two\n\n```\nlet x = 1\n```\n', 'src/a.txt': 'line one\nline two\n', 'b.txt': 'b\n' }, (git, work) => {writeFileSync(join(work, 'src', 'a.txt'), 'changed\n'); git('commit', '-qam', '|||PR add a change');});const lines = ['# A long README', ''];for (let i = 1; lines.length < 2003; i++) lines.push(`## Section ${i}`, '', `Paragraph ${i} with **strong**, *soft*, \`code\` and a [link](https://example.org/${i}) to show inline work.`, '', `- item ${i}.1`, `- item ${i}.2`, '');push('longdoc', { 'README.md': lines.join('\n') + '\n' });}// ---- measuring ---------------------------------------------------------------------------------------const OBSERVE = `(() => {window.__mo && window.__mo.disconnect();const c = (n) => n.nodeType === 1 ? 1 + n.getElementsByTagName('*').length : 0;window.__cnt = { removed: 0, added: 0 }; window.__lt = 0;window.__mo = new MutationObserver((recs) => { for (const r of recs) { for (const n of r.removedNodes) window.__cnt.removed += c(n); for (const n of r.addedNodes) window.__cnt.added += c(n); } });window.__mo.observe(document.body, { childList: true, subtree: true });try { window.__po && window.__po.disconnect(); window.__po = new PerformanceObserver((l) => { for (const e of l.getEntries()) window.__lt += e.duration; }); window.__po.observe({ entryTypes: ['longtask'] }); } catch {}return true; })()`;// tag the standing candidates; compare after the click (same object? still connected?)const TAG = `(() => { const q = (s) => document.querySelector(s); const m = { shell: q('main'), repoPage: q('main repo-page'), head: q('repo-head'), name: q('#reponame'), nav: q('#reponav'),navlinks: q('#reponav a'), header: q('application-header'), page: q('main repo-page > :last-child') };window.__tags = m; window.__ids = {}; for (const k in m) { if (m[k]) m[k].__tag = k + '#' + Math.random().toString(36).slice(2); window.__ids[k] = m[k] ? m[k].__tag : null; } return window.__ids; })()`;const CHECK = `(() => { const q = (s) => document.querySelector(s); const now = { shell: q('main'), repoPage: q('main repo-page'), head: q('repo-head'), name: q('#reponame'), nav: q('#reponav'),navlinks: q('#reponav a'), header: q('application-header'), page: q('main repo-page > :last-child') }; const r = {};for (const k in now) r[k] = !!now[k] && !!window.__ids[k] && now[k].__tag === window.__ids[k] && now[k].isConnected; return r; })()`;async function steps(P, vp, slug) {const rows = [];await P.goto(REPO(slug) + '/'); await P.waitFor('!!document.querySelector("#homepage")', { label: 'readme' }); await hydrated(P); await sleep(500);await P.evaluate(TAG);const seq = [['#navcode', '/code', '#entries', 'Readme→Code'], ['#navpulls', '/pulls', '#pullshelp', 'Code→Pulls'], ['#navhome', '/', '#homepage', 'Pulls→Readme'], ['#navcode', '/code', '#entries', 'Readme→Code (2nd)']];let n = 0;await P.evaluate(OBSERVE);rows.push({ shot: await shot(P, `${vp}-0-readme`) });for (const [link, path, sel, name] of seq) {await P.evaluate('window.__cnt.removed = 0; window.__cnt.added = 0; window.__lt = 0; 0');await P.click(link);await P.waitFor(`location.pathname === ${J(path)} && !!document.querySelector(${J(sel)})`, { label: name, timeout: 30000 });await sleep(700); // let the page settle: late additions are counted tooconst cnt = await P.evaluate('({ ...window.__cnt, longtask: Math.round(window.__lt) })');const kept = await P.evaluate(CHECK);const cur = await P.evaluate(`[...document.querySelectorAll('#reponav a[aria-current=page]')].map(a => a.id).join()`);rows.push({ step: name, ...cnt, kept, aria: cur, shot: await shot(P, `${vp}-${++n}-${path.replace(/\W/g, '') || 'readme'}`) });}return rows;}async function timing(P, vp) {const res = [];for (let i = 0; i < 3; i++) {await P.goto(REPO('longdoc') + '/code'); await P.waitFor('!!document.querySelector("#codemessage, #entries, #noentries")', { label: 'longdoc code', timeout: 60000 }); await hydrated(P); await sleep(800);await P.evaluate(OBSERVE);// page-side stopwatch: starts at the click's `pointerdown` (the real press), stops when the README text is in the DOM and painted (2 rAF)await P.evaluate(`(() => { window.__tm = { done: false }; const a = document.querySelector('#navhome');a.addEventListener('pointerdown', () => { window.__tm.t0 = performance.now(); const poll = () => { const m = document.querySelector('#homepage markdown-text'); if (m && m.querySelector('h2')) { requestAnimationFrame(() => requestAnimationFrame(() => { window.__tm.shown = performance.now() - window.__tm.t0; window.__tm.done = true; })); } else requestAnimationFrame(poll); }; poll(); }, { once: true }); return true; })()`);await P.click('#navhome');await P.waitFor('window.__tm.done', { timeout: 60000, label: 'readme shown' });await sleep(500);const t = await P.evaluate('({ shown: Math.round(window.__tm.shown), removed: window.__cnt.removed, added: window.__cnt.added, longtask: Math.round(window.__lt) })');res.push(t);}return { vp, runs: res };}const SERVE = process.env.CHAIN_SERVE === '1', MEASURE_ONLY = process.env.CHAIN_MEASURE === '1';try {if (!MEASURE_ONLY) {rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });const alice = await ident.signIn('[email protected]');const KEY = await ident.registerApp(alice, 'gitoria (chain)', [BASE]);startServer({ IDENT_API_KEY: KEY.key, IDENT_API_SECRET: KEY.secret });await serverUp();await seed();if (SERVE) {console.log('READY ' + BASE);await new Promise((r) => { process.on('SIGTERM', r); process.on('SIGINT', r); });throw new Error('stopped');}}// the measuring browserlet P, B, own = true, keepUa = null;if (process.env.CHAIN_CDP) {process.env.HL_CDP_URL = process.env.CHAIN_CDP; B = await launchBrowser();const { targetInfos } = await B.conn.send('Target.getTargets');const t = targetInfos.find(x => x.type === 'page');const { sessionId } = await B.conn.send('Target.attachToTarget', { targetId: t.targetId, flatten: true });P = new Page(B, t.targetId, sessionId); await P._init(); own = false;await P.send('Page.bringToFront'); // a background tab paints no frames: no screenshots, no requestAnimationFrame} else { B = await launchBrowser({ debugPortRange: CHROME_PORTS }); P = await B.newPage(); }for (const [vp, w, h, mobile] of [['desktop', 1280, 900, false], ['phone390', 390, 844, true]]) {await P.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: mobile ? 2 : 1, mobile });await sleep(300);const rows = await steps(P, vp, 'alpha');out.steps.push({ vp, rows });if (vp === 'phone390') {out.tapSizes = await P.evaluate(`[...document.querySelectorAll('#reponav a')].map(a => { const r = a.getBoundingClientRect(); return a.id + ':' + Math.round(r.width) + 'x' + Math.round(r.height); })`);out.noOverflow = await P.evaluate('document.documentElement.scrollWidth <= 390');}out.timing.push(await timing(P, vp));}await P.send('Emulation.clearDeviceMetricsOverride');writeFileSync(join(SCRATCH, `chain-${LABEL}.json`), J(out, null, 1));for (const s of out.steps) for (const r of s.rows) if (r.step) console.log(`${LABEL} ${s.vp.padEnd(9)} ${r.step.padEnd(22)} removed ${String(r.removed).padStart(4)} added ${String(r.added).padStart(4)} longtask ${r.longtask}ms aria-current=${r.aria} SAME NODE: ` + Object.entries(r.kept).map(([k, v]) => k + '=' + (v ? 'yes' : 'NO')).join(' '));for (const t of out.timing) console.log(`${LABEL} ${t.vp.padEnd(9)} longdoc Readme click→text painted (ms): ` + t.runs.map(r => `${r.shown} (removed ${r.removed}/added ${r.added}, longtask ${r.longtask})`).join(' | '));if (out.tapSizes) console.log(`${LABEL} phone tabs: ${out.tapSizes.join(' ')} no-overflow=${out.noOverflow}`);await B.close();} catch (e) { if (e.message !== 'stopped') { console.log('CHAIN FAILED ' + (e && e.stack || e)); process.exitCode = 1; } }finally {if (server) { try { server.kill('SIGTERM'); } catch {} }if (ident) await ident.stop();if (!MEASURE_ONLY) writeFileSync(join(SCRATCH, `chain-${LABEL}-server.log`), log);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