gitoria
All repositories: gitoria
14.9 KB
// 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 = Number(process.env.CHAIN_PORT || 8720);const IDENT_PORT = Number(process.env.CHAIN_IDENT_PORT || 8721);const CHROME_PORTS = (process.env.CHAIN_CHROME || '8722-8724').split('-').map(Number);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', { 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) .choose');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 .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
- f1-broken-json
- f2-api-bugs
- gp-gate-ports
- heap-revert
- hl25-records
- ident-chooser-selector
- mainmain branch
- p51-public-pr-reads
- records-1112
- s25-no-session-on-login-error
- v59
- w52-person-approval
- w52b-approval-followup
- w52c-header-phone
- w53-pulls-speed-pr
- w54-repo-rename-pr
- w55-rename-org
- w56-owner-members
- w62-pr-close
- w63-force-push
Latest commits
- 00517fafgitoria: shell 404 page for unknown paths (catch-all route, status 404, JSON 404 under /api), 390 gate checksMG
- d9e977f0reports/MG-mobile.md, LOGMG
- 2f2725actests/browser.mjs: commit-row check (one row, centred date)MG
- 4df1ea01tests/browser.mjs: MG phone checks (list first, no dead strip, one branch heading, tab grid, commit rows, PR title row, ticket columns, wrapping commands)MG
- c52424e9gitoria mobile: repo list before the forms, 3x2 tab grid, no duplicate branch heading, ordered commit rows, aligned ticket rows, pull title on its own row, wrapping clone commands, no dead strip under formsMG
- 3a95252dG3: cache parsed README blocks by sha256 of the text (bounded LRU), reportmre
- 570138cddeploy: security gate (tests/security.mjs)mre
- da6b20fcgitoria SG: security audit fixes (uploadMax 0, Secure cookie on https, session rotation at login, nosniff on function routes, no identity in page data) + tests/security.mjs gate + reportmre
- f98c981fgitoria B1: report wordingmre
- c6364cedgitoria B1: compact Markdown blocks (one kind flag per block/span, empty and false fields omitted); same rendered HTML, page values -67%mre
- cd99d2feWIP gitoria#22: always render the repo level's slot (missing-repo boot hang), pages render nothing without a repo; hydration diagnosis in reports/G2-hydrate.mdmre
- e5404b9breport: commit idsmre
- 63cfa21ereports/G2-repotabs.mdmre
- 9b0516fdgitoria#22: mark the tab underline functional (check-theme), chain E2E: serve/measure split, bring the lisbeth tab to frontmre
- 19bc1df8gitoria#22: all repo pages under ONE layout level (components/repo.hl, hl:web D-CHAIN): a tab click replaces only the page in the slot; head and tab nav stay the same DOM nodesmre
- 40658417tests/browser.mjs: wait for the page to be live (hydrated) before clicking Merge — a click on the server-rendered button before the client mounted was lost (flaky 'Clashing change' under load)mre
- 48a6154bre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
- e972e8d7tests: short-id-switch (GITORIA_SWITCH_IDENT_PORT/_PORT) and ssh tunnel (GITORIA_GATE_TUNNEL_PORT) ports from env, defaults unchangedmre
- f06f5349re-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
- c7d3cc87docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre