gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit220a80e0220a80e0|||PR Remove temporary /__heap route and heap helper; logmre220a80e0/tests/chain.mjs

15.0 KB

  1. // tests/chain.mjs — gitoria#22: WHAT A TAB CLICK REPLACES, MEASURED IN A REAL CHROME WITH REAL CLICKS (C2's method).
  2. // Own ident + gitoria on a copy of the data (localhost hosts: alpha.localhost resolves to 127.0.0.1 in Chrome itself). Seeds repos
  3. // `alpha` (README, code, a branch, a pull request), `longdoc` (a 2 003-line README) and `gamma` (empty) through the real UI.
  4. // Then, in the measuring browser, per viewport: Readme → Code → Pulls → Readme → Code on alpha with real clicks, a
  5. // MutationObserver counting the elements REMOVED / ADDED by each click, and the repo head, the tab nav and the page elements tagged with
  6. // a property BEFORE the click — after the click they must still be the SAME node objects (standing levels). Then the
  7. // README timing on `longdoc` (click Code → click Readme: click → README text in the DOM, long-task time, page-side).
  8. // Results: .scratch/chain-<label>.json + a table on stdout. Screenshots .scratch/chain-<label>-<viewport>-<step>.png.
  9. // CHAIN_SERVE=1 only seed + serve (prints READY, runs until SIGTERM) — start it OUTSIDE the lisbeth lock; CHAIN_MEASURE=1 only measure an
  10. // already serving app on CHAIN_PORT (the E2E part that goes under the lock).
  11. // CHAIN_APP=<app dir> the code under test (default: this app); CHAIN_LABEL=old|new; CHAIN_PORT=8720 CHAIN_IDENT_PORT=8721
  12. // 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
  13. // closed) — run it under `flock …/lisbeth.lock`. Without it a headless Chrome is launched.
  14. import { spawn, execFileSync } from 'node:child_process';
  15. import { rmSync, mkdirSync, writeFileSync, existsSync } from 'node:fs';
  16. import { dirname, join, resolve } from 'node:path';
  17. import { fileURLToPath } from 'node:url';
  18. import { launchBrowser, Page } from './cdp.mjs';
  19. import { startIdent } from './identkit.mjs';
  20. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  21. const HERE = dirname(fileURLToPath(import.meta.url));
  22. const OWN = resolve(HERE, '..');
  23. const APP = resolve(process.env.CHAIN_APP || OWN);
  24. const LABEL = process.env.CHAIN_LABEL || 'run';
  25. const PORT = Number(process.env.CHAIN_PORT || 8720);
  26. const IDENT_PORT = Number(process.env.CHAIN_IDENT_PORT || 8721);
  27. const CHROME_PORTS = (process.env.CHAIN_CHROME || '8722-8724').split('-').map(Number);
  28. const BASE = `http://localhost:${PORT}`;
  29. const REPO = (s) => `http://${s}.localhost:${PORT}`;
  30. const IDENT_B = `http://localhost:${IDENT_PORT}`;
  31. const SCRATCH = join(OWN, '.scratch');
  32. const STORE = join(SCRATCH, 'chain-store-' + LABEL);
  33. const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || '/media/STORAGE/projects/WorldAPI/ident.worldapi.org';
  34. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  35. const J = JSON.stringify;
  36. mkdirSync(SCRATCH, { recursive: true });
  37. let server = null, ident = null, log = '';
  38. const out = { label: LABEL, app: APP, steps: [], timing: [] };
  39. function startServer(env) {
  40. server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  41. 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'),
  42. GITORIA_PUBLIC_URL: BASE, IDENT_URL: IDENT_B, IDENT_EXCHANGE_URL: ident.base, ...env } });
  43. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  44. }
  45. async function serverUp() {
  46. 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); }
  47. throw new Error('gitoria did not come up\n' + log);
  48. }
  49. const hydrated = (p) => p.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'hydrated', timeout: 60000 });
  50. 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; };
  51. async function seed() {
  52. const b = await launchBrowser({ debugPortRange: CHROME_PORTS });
  53. const A = await b.newPage();
  54. try {
  55. await A.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  56. await A.goto(IDENT_B + '/'); await A.waitForSelector('#email'); await hydrated(A);
  57. await A.type('#email', '[email protected]'); await A.click('#sendcode');
  58. await A.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'ident code page' }); await hydrated(A);
  59. await A.type('#code', ident.lastCode('[email protected]')); await A.click('#verify'); await A.waitForSelector('#signout, #menusignout', { timeout: 15000 });
  60. await A.goto(BASE + '/'); await A.waitForSelector('#loginbutton'); await hydrated(A);
  61. await A.click('#loginbutton'); await A.waitForSelector('#chooselist', { timeout: 15000 }); await hydrated(A); await A.click('#chooselist li:nth-child(1) .choose');
  62. await A.waitFor(`location.href === ${J(BASE + '/')} && !!document.querySelector("#nameform")`, { label: 'name prompt' }); await hydrated(A);
  63. await A.type('#displayname', 'alice'); await A.click('#namesave'); await A.waitFor('!document.querySelector("#nameform")'); await A.waitForSelector('#createform');
  64. for (const slug of ['alpha', 'longdoc', 'gamma']) {
  65. for (let attempt = 1; ; attempt++) { // a loaded machine drops a click now and then: look, then retry
  66. await A.evaluate('document.querySelector("#slug").value = ""; document.querySelector("#description").value = ""');
  67. await A.type('#slug', slug); await A.type('#description', 'repo ' + slug); await A.click('#createsave');
  68. try { await A.waitFor(`[...document.querySelectorAll('#repos .repo-slug')].some(a => a.textContent === ${J(slug)})`, { label: 'created ' + slug, timeout: 30000 }); break; }
  69. catch (e) { if (attempt >= 3) throw e; }
  70. }
  71. }
  72. } finally { await b.close(); }
  73. const push = (slug, files, extra = () => {}) => {
  74. const work = join(STORE, 'work-' + slug); rmSync(work, { recursive: true, force: true }); mkdirSync(work, { recursive: true });
  75. const git = (...a) => execFileSync('git', ['-C', work, '-c', 'user.name=t', '-c', '[email protected]', ...a], { stdio: 'pipe' });
  76. git('init', '-q', '-b', 'main');
  77. for (const [p, c] of Object.entries(files)) { mkdirSync(dirname(join(work, p)), { recursive: true }); writeFileSync(join(work, p), c); }
  78. git('add', '-A'); git('commit', '-q', '-m', 'files'); extra(git, work);
  79. git('push', '-q', '-f', join(STORE, 'git', slug + '.git'), '--all');
  80. };
  81. 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) => {
  82. writeFileSync(join(work, 'src', 'a.txt'), 'changed\n'); git('commit', '-qam', '|||PR add a change');
  83. });
  84. const lines = ['# A long README', ''];
  85. 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`, '');
  86. push('longdoc', { 'README.md': lines.join('\n') + '\n' });
  87. }
  88. // ---- measuring ---------------------------------------------------------------------------------------
  89. const OBSERVE = `(() => {
  90. window.__mo && window.__mo.disconnect();
  91. const c = (n) => n.nodeType === 1 ? 1 + n.getElementsByTagName('*').length : 0;
  92. window.__cnt = { removed: 0, added: 0 }; window.__lt = 0;
  93. 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); } });
  94. window.__mo.observe(document.body, { childList: true, subtree: true });
  95. 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 {}
  96. return true; })()`;
  97. // tag the standing candidates; compare after the click (same object? still connected?)
  98. 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'),
  99. navlinks: q('#reponav a'), header: q('application-header'), page: q('main repo-page > :last-child') };
  100. 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; })()`;
  101. 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'),
  102. navlinks: q('#reponav a'), header: q('application-header'), page: q('main repo-page > :last-child') }; const r = {};
  103. for (const k in now) r[k] = !!now[k] && !!window.__ids[k] && now[k].__tag === window.__ids[k] && now[k].isConnected; return r; })()`;
  104. async function steps(P, vp, slug) {
  105. const rows = [];
  106. await P.goto(REPO(slug) + '/'); await P.waitFor('!!document.querySelector("#homepage")', { label: 'readme' }); await hydrated(P); await sleep(500);
  107. await P.evaluate(TAG);
  108. const seq = [['#navcode', '/code', '#entries', 'Readme→Code'], ['#navpulls', '/pulls', '#pullshelp', 'Code→Pulls'], ['#navhome', '/', '#homepage', 'Pulls→Readme'], ['#navcode', '/code', '#entries', 'Readme→Code (2nd)']];
  109. let n = 0;
  110. await P.evaluate(OBSERVE);
  111. rows.push({ shot: await shot(P, `${vp}-0-readme`) });
  112. for (const [link, path, sel, name] of seq) {
  113. await P.evaluate('window.__cnt.removed = 0; window.__cnt.added = 0; window.__lt = 0; 0');
  114. await P.click(link);
  115. await P.waitFor(`location.pathname === ${J(path)} && !!document.querySelector(${J(sel)})`, { label: name, timeout: 30000 });
  116. await sleep(700); // let the page settle: late additions are counted too
  117. const cnt = await P.evaluate('({ ...window.__cnt, longtask: Math.round(window.__lt) })');
  118. const kept = await P.evaluate(CHECK);
  119. const cur = await P.evaluate(`[...document.querySelectorAll('#reponav a[aria-current=page]')].map(a => a.id).join()`);
  120. rows.push({ step: name, ...cnt, kept, aria: cur, shot: await shot(P, `${vp}-${++n}-${path.replace(/\W/g, '') || 'readme'}`) });
  121. }
  122. return rows;
  123. }
  124. async function timing(P, vp) {
  125. const res = [];
  126. for (let i = 0; i < 3; i++) {
  127. 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);
  128. await P.evaluate(OBSERVE);
  129. // 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)
  130. await P.evaluate(`(() => { window.__tm = { done: false }; const a = document.querySelector('#navhome');
  131. 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; })()`);
  132. await P.click('#navhome');
  133. await P.waitFor('window.__tm.done', { timeout: 60000, label: 'readme shown' });
  134. await sleep(500);
  135. const t = await P.evaluate('({ shown: Math.round(window.__tm.shown), removed: window.__cnt.removed, added: window.__cnt.added, longtask: Math.round(window.__lt) })');
  136. res.push(t);
  137. }
  138. return { vp, runs: res };
  139. }
  140. const SERVE = process.env.CHAIN_SERVE === '1', MEASURE_ONLY = process.env.CHAIN_MEASURE === '1';
  141. try {
  142. if (!MEASURE_ONLY) {
  143. rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  144. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  145. const alice = await ident.signIn('[email protected]');
  146. const KEY = await ident.registerApp(alice, 'gitoria (chain)', [BASE]);
  147. startServer({ IDENT_API_KEY: KEY.key, IDENT_API_SECRET: KEY.secret });
  148. await serverUp();
  149. await seed();
  150. if (SERVE) {
  151. console.log('READY ' + BASE);
  152. await new Promise((r) => { process.on('SIGTERM', r); process.on('SIGINT', r); });
  153. throw new Error('stopped');
  154. }
  155. }
  156. // the measuring browser
  157. let P, B, own = true, keepUa = null;
  158. if (process.env.CHAIN_CDP) {
  159. process.env.HL_CDP_URL = process.env.CHAIN_CDP; B = await launchBrowser();
  160. const { targetInfos } = await B.conn.send('Target.getTargets');
  161. const t = targetInfos.find(x => x.type === 'page');
  162. const { sessionId } = await B.conn.send('Target.attachToTarget', { targetId: t.targetId, flatten: true });
  163. P = new Page(B, t.targetId, sessionId); await P._init(); own = false;
  164. await P.send('Page.bringToFront'); // a background tab paints no frames: no screenshots, no requestAnimationFrame
  165. } else { B = await launchBrowser({ debugPortRange: CHROME_PORTS }); P = await B.newPage(); }
  166. for (const [vp, w, h, mobile] of [['desktop', 1280, 900, false], ['phone390', 390, 844, true]]) {
  167. await P.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: mobile ? 2 : 1, mobile });
  168. await sleep(300);
  169. const rows = await steps(P, vp, 'alpha');
  170. out.steps.push({ vp, rows });
  171. if (vp === 'phone390') {
  172. 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); })`);
  173. out.noOverflow = await P.evaluate('document.documentElement.scrollWidth <= 390');
  174. }
  175. out.timing.push(await timing(P, vp));
  176. }
  177. await P.send('Emulation.clearDeviceMetricsOverride');
  178. writeFileSync(join(SCRATCH, `chain-${LABEL}.json`), J(out, null, 1));
  179. 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(' '));
  180. 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(' | '));
  181. if (out.tapSizes) console.log(`${LABEL} phone tabs: ${out.tapSizes.join(' ')} no-overflow=${out.noOverflow}`);
  182. await B.close();
  183. } catch (e) { if (e.message !== 'stopped') { console.log('CHAIN FAILED ' + (e && e.stack || e)); process.exitCode = 1; } }
  184. finally {
  185. if (server) { try { server.kill('SIGTERM'); } catch {} }
  186. if (ident) await ident.stop();
  187. if (!MEASURE_ONLY) writeFileSync(join(SCRATCH, `chain-${LABEL}-server.log`), log);
  188. process.exit(process.exitCode || 0);
  189. }

Branches

Latest commits

  • 220a80e0|||PR Remove temporary /__heap route and heap helper; logmre
  • 13f0c342Merge branch 'hl25-records' into mainGitoria
  • a002ecb7|||PR records: HL25 report, heap helper, logmre
  • 2492a55cTemporary keyed /__heap route for the live memory snapshotmre
  • fefaedd2log: tracker PR-only, HL25 startedmre
  • 21aa57calog: parkmre
  • e9f950a8reports: G25c soakmre
  • a7783686log: deploy 9f41ffcmre
  • 9f41ffc1log: W30b mergedmre
  • bef635c1Merge branch 'w30b'mre
  • 15b996a5Org list: keyed rows by @id, newest first, concat instead of hand loopmre
  • c4f6d9e3reports: G25c growth huntmre
  • b88e39f1log: privacy cleanup donemre
  • bfd7826ddocs: neutral example organisation namemre
  • 01b71c2edocs: neutral wording in missions, reports and logmre
  • 3eeea733log: 2026-11-09 PR flow plan and membersmre
  • e7c2ff1fdocs: neutral name for the apps-api reviewmre
  • 120b7abdlog: step 3 queuedmre
  • 358474bflog: P50 livemre
  • 477d7bdcMerge branch 'p50'mre